anthropic API Reference
Full documentation for anthropic (0.120.2)
anthropic.AI_PROMPT
Error rendering doc: No Python documentation found for '\n\nAssistant:'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
anthropic.APIConnectionError
Python Library Documentation: class APIConnectionError in module anthropic
class APIConnectionError(APIError)
| APIConnectionError(*, message: 'str' = 'Connection error.', request: 'httpx.Request') -> 'None'
|
| Method resolution order:
| APIConnectionError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, message: 'str' = 'Connection error.', request: 'httpx.Request') -> 'None' from anthropic._exceptions.APIConnectionError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.APIError
Python Library Documentation: class APIError in module anthropic
class APIError(AnthropicError)
| APIError(message: 'str', request: 'httpx.Request', *, body: 'object | None') -> 'None'
|
| Method resolution order:
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str', request: 'httpx.Request', *, body: 'object | None') -> 'None' from anthropic._exceptions.APIError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'body': 'object | None', 'message': 'str', 'request...
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.APIRequest
Python Library Documentation: class APIRequest in module anthropic class APIRequest(builtins.object) | APIRequest(*, options: 'FinalRequestOptions', cast_to: 'Any', stream: 'bool' = False, stream_cls: 'type[Any] | None' = None, retries_taken: 'int' = 0) -> 'None' | | A view over the request that the client is about to execute. | | Treat instances as immutable; use `copy()` to derive a modified request. | | Methods defined here: | | __init__(self, *, options: 'FinalRequestOptions', cast_to: 'Any', stream: 'bool' = False, stream_cls: 'type[Any] | None' = None, retries_taken: 'int' = 0) -> 'None' from anthropic._request.APIRequest | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) -> 'str' from anthropic._request.APIRequest | Return repr(self). | | copy(self, *, method: 'str | NotGiven' = NOT_GIVEN, url: 'str | NotGiven' = NOT_GIVEN, headers: 'Headers | NotGiven' = NOT_GIVEN, params: 'Query | NotGiven' = NOT_GIVEN, body: 'Body | NotGiven' = NOT_GIVEN, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'APIRequest' from anthropic._request.APIRequest | | ---------------------------------------------------------------------- | Readonly properties defined here: | | headers | | json | | max_retries | | method | | query_params | | timeout | | url | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.APIResponse
Python Library Documentation: class APIResponse in module anthropic._response
class APIResponse(BaseAPIResponse)
| APIResponse(*, raw: 'httpx.Response', cast_to: 'type[R]', client: 'BaseClient[Any, Any]', stream: 'bool', stream_cls: 'type[Stream[Any]] | type[AsyncStream[Any]] | None', options: 'FinalRequestOptions', retries_taken: 'int' = 0) -> 'None'
|
| Method resolution order:
| APIResponse
| BaseAPIResponse
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| close(self) -> 'None'
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| iter_bytes(self, chunk_size: 'int | None' = None) -> 'Iterator[bytes]'
| A byte-iterator over the decoded response content.
|
| This automatically handles gzip, deflate and brotli encoded responses.
|
| iter_lines(self) -> 'Iterator[str]'
| Like `iter_text()` but will only yield chunks for each line
|
| iter_text(self, chunk_size: 'int | None' = None) -> 'Iterator[str]'
| A str-iterator over the decoded response content
| that handles both gzip, deflate, etc but also detects the content's
| string encoding.
|
| json(self) -> 'object'
| Read and decode the JSON response content.
|
| parse(self, *, to: 'type[_T] | None' = None) -> 'R | _T'
| Returns the rich python representation of this response's data.
|
| For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
|
| You can customise the type that the response is parsed into through
| the `to` argument, e.g.
|
| ```py
| from anthropic import BaseModel
|
|
| class MyModel(BaseModel):
| foo: str
|
|
| obj = response.parse(to=MyModel)
| print(obj.foo)
| ```
|
| We support parsing:
| - `BaseModel`
| - `dict`
| - `list`
| - `Union`
| - `str`
| - `int`
| - `float`
| - `httpx.Response`
|
| read(self) -> 'bytes'
| Read and return the binary response content.
|
| text(self) -> 'str'
| Read and decode the response content into a string.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| request_id
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (anthropic._response.BaseAPIResponse[~R],)
|
| __parameters__ = (~R,)
|
| ----------------------------------------------------------------------
| Methods inherited from BaseAPIResponse:
|
| __init__(self, *, raw: 'httpx.Response', cast_to: 'type[R]', client: 'BaseClient[Any, Any]', stream: 'bool', stream_cls: 'type[Stream[Any]] | type[AsyncStream[Any]] | None', options: 'FinalRequestOptions', retries_taken: 'int' = 0) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseAPIResponse:
|
| elapsed
| The time taken for the complete request/response cycle to complete.
|
| headers
|
| http_request
| Returns the httpx Request instance associated with the current response.
|
| http_version
|
| is_closed
| Whether or not the response body has been closed.
|
| If this is False then there is response data that has not been read yet.
| You must either fully consume the response body or call `.close()`
| before discarding the response to prevent resource leaks.
|
| method
|
| status_code
|
| url
| Returns the URL for which the request was made.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseAPIResponse:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.APIResponseValidationError
Python Library Documentation: class APIResponseValidationError in module anthropic
class APIResponseValidationError(APIError)
| APIResponseValidationError(response: 'httpx.Response', body: 'object | None', *, message: 'str | None' = None) -> 'None'
|
| Method resolution order:
| APIResponseValidationError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, response: 'httpx.Response', body: 'object | None', *, message: 'str | None' = None) -> 'None' from anthropic._exceptions.APIResponseValidationError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'response': 'httpx.Response', 'status_code': 'int'}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.APIStatusError
Python Library Documentation: class APIStatusError in module anthropic
class APIStatusError(APIError)
| APIStatusError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Raised when an API response has a status code of 4xx or 5xx.
|
| Method resolution order:
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'request_id': 'str | None', 'response': 'httpx.Resp...
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.APITimeoutError
Python Library Documentation: class APITimeoutError in module anthropic
class APITimeoutError(APIConnectionError)
| APITimeoutError(request: 'httpx.Request') -> 'None'
|
| Method resolution order:
| APITimeoutError
| APIConnectionError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, request: 'httpx.Request') -> 'None' from anthropic._exceptions.APITimeoutError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.APIWebhookValidationError
Python Library Documentation: class APIWebhookValidationError in module anthropic
class APIWebhookValidationError(APIError)
| APIWebhookValidationError(message: 'str', request: 'httpx.Request', *, body: 'object | None') -> 'None'
|
| Method resolution order:
| APIWebhookValidationError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from APIError:
|
| __init__(self, message: 'str', request: 'httpx.Request', *, body: 'object | None') -> 'None' from anthropic._exceptions.APIError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.AccessToken
Python Library Documentation: class AccessToken in module anthropic.lib.credentials._types
class AccessToken(builtins.object)
| AccessToken(token: 'str', expires_at: 'Optional[int]' = None) -> None
|
| An Anthropic API access token with optional expiry.
|
| ``expires_at`` is unix seconds; ``None`` means no expiry information
| (the token will be treated as never-expires by :class:`TokenCache`).
|
| ``repr()`` masks the token (at most its last four characters) so a frame
| or log line holding an ``AccessToken`` never exposes the raw value —
| crash reporters that capture traceback locals render their ``repr``.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, token: 'str', expires_at: 'Optional[int]' = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'expires_at': 'Optional[int]', 'token': 'str'}
|
| __dataclass_fields__ = {'expires_at': Field(name='expires_at',type='Op...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('token', 'expires_at')
|
| expires_at = None
anthropic.AccessTokenAuth
Python Library Documentation: class AccessTokenAuth in module anthropic.lib.credentials._auth class AccessTokenAuth(httpx.Auth) | AccessTokenAuth(token_cache: 'TokenCache') -> 'None' | | Adapts a :class:`TokenCache` to httpx's :class:`~httpx.Auth` protocol. | | Used by :meth:`anthropic.Anthropic.custom_auth` to inject ``Authorization: Bearer`` | plus the OAuth beta header on every request, with proactive refresh handled by | :class:`TokenCache`. | | Static credentials shadow federation: if the outgoing request already carries | an ``X-Api-Key`` or ``Authorization`` header (set by the client's api_key / | auth_token path), this auth flow is a no-op. That matches the Go SDK's | ``authMiddleware`` and the documented precedence in the WIF user guide — | a static ``ANTHROPIC_API_KEY`` shadows any credentials provider. | | Method resolution order: | AccessTokenAuth | httpx.Auth | builtins.object | | Methods defined here: | | __init__(self, token_cache: 'TokenCache') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | async async_auth_flow(self, request: 'httpx.Request') -> 'AsyncGenerator[httpx.Request, httpx.Response]' | Execute the authentication flow asynchronously. | | By default, this defers to `.auth_flow()`. You should override this method | when the authentication scheme does I/O and/or uses concurrency primitives. | | sync_auth_flow(self, request: 'httpx.Request') -> 'Generator[httpx.Request, httpx.Response, None]' | Execute the authentication flow synchronously. | | By default, this defers to `.auth_flow()`. You should override this method | when the authentication scheme does I/O and/or uses concurrency primitives. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | requires_response_body = False | | ---------------------------------------------------------------------- | Methods inherited from httpx.Auth: | | auth_flow(self, request: 'Request') -> 'typing.Generator[Request, Response, None]' from httpx._auth.Auth | Execute the authentication flow. | | To dispatch a request, `yield` it: | | ``` | yield request | ``` | | The client will `.send()` the response back into the flow generator. You can | access it like so: | | ``` | response = yield request | ``` | | A `return` (or reaching the end of the generator) will result in the | client returning the last response obtained from the server. | | You can dispatch as many requests as is necessary. | | ---------------------------------------------------------------------- | Data descriptors inherited from httpx.Auth: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes inherited from httpx.Auth: | | requires_request_body = False
anthropic.AccessTokenProvider
Python Library Documentation: class AccessTokenProvider in module anthropic.lib.credentials._types
class AccessTokenProvider(typing.Protocol)
| AccessTokenProvider(*args, **kwargs)
|
| Callable that mints or returns a cached access token.
|
| Re-invoking the provider IS the refresh mechanism — providers have no
| separate ``refresh()`` method. Providers may be stateful (hold config /
| paths) but the *cache* lives in :class:`TokenCache`, not here.
|
| The optional ``force_refresh`` flag is set by
| :meth:`TokenCache.invalidate` after a 401: providers with on-disk caches
| (user_oauth, oidc_federation) must bypass their freshness short-circuit
| and always fetch fresh when it is True. Providers without a cache can
| accept and ignore the flag.
|
| Method resolution order:
| AccessTokenProvider
| typing.Protocol
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __call__(self, *, force_refresh: 'bool' = False) -> 'AccessToken'
| Call self as a function.
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs) from typing
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other) from typing
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__call__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
anthropic.Anthropic
Python Library Documentation: class Anthropic in module anthropic
class Anthropic(anthropic._base_client.SyncAPIClient)
| Anthropic(*, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None'
|
| Method resolution order:
| Anthropic
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None' from anthropic._client.Anthropic
| Construct a new synchronous Anthropic client instance.
|
| Credentials are resolved in the following order (first match wins):
|
| 1. Explicit constructor arguments — ``api_key=``, ``auth_token=``,
| ``credentials=``, ``config=``, or ``profile=``. When any of these
| is passed, environment variables are not consulted for credentials.
| 2. ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` environment
| variables.
| 3. ``ANTHROPIC_PROFILE`` environment variable — loads the named
| profile from ``<config_dir>/configs/<profile>.json``.
| 4. Workload identity federation environment variables —
| ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` +
| ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID``.
| 5. The active profile on disk — the profile named by
| ``<config_dir>/active_config``, or ``default``.
|
| ``credentials=``, ``config=``, and ``profile=`` are mutually exclusive.
|
| If a static credential is supplied alongside a credentials provider
| (``credentials=`` / ``config=`` / ``profile=``), or if
| ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside a
| profile or federation configuration, the static credential takes
| precedence and a one-shot warning is logged on the ``anthropic``
| logger.
|
| beta = <functools.cached_property object>
| close(self) -> 'None' from anthropic._client.Anthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self' from anthropic._client.Anthropic
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.Anthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| __annotations__ = {'_custom_auth': 'AccessTokenAuth | None', '_token_c...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| __orig_bases__ = (anthropic._base_client.BaseClient[httpx.Client, anth...
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AnthropicAWS
Python Library Documentation: class AnthropicAWS in module anthropic.lib.aws._client
class AnthropicAWS(anthropic.Anthropic)
| AnthropicAWS(*, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, auth_token: 'str | None' = None, webhook_key: 'str | None' = None) -> 'None'
|
| Method resolution order:
| AnthropicAWS
| anthropic.Anthropic
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, auth_token: 'str | None' = None, webhook_key: 'str | None' = None) -> 'None'
| Construct a new synchronous Anthropic client instance.
|
| Credentials are resolved in the following order (first match wins):
|
| 1. Explicit constructor arguments — ``api_key=``, ``auth_token=``,
| ``credentials=``, ``config=``, or ``profile=``. When any of these
| is passed, environment variables are not consulted for credentials.
| 2. ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` environment
| variables.
| 3. ``ANTHROPIC_PROFILE`` environment variable — loads the named
| profile from ``<config_dir>/configs/<profile>.json``.
| 4. Workload identity federation environment variables —
| ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` +
| ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID``.
| 5. The active profile on disk — the profile named by
| ``<config_dir>/active_config``, or ``default``.
|
| ``credentials=``, ``config=``, and ``profile=`` are mutually exclusive.
|
| If a static credential is supplied alongside a credentials provider
| (``credentials=`` / ``config=`` / ``profile=``), or if
| ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside a
| profile or federation configuration, the static credential takes
| precedence and a one-shot warning is logged on the ``anthropic``
| logger.
|
| copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_options = copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| default_headers
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_skip_auth': 'bool', '_use_sigv4': 'bool', 'aws_ac...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.Anthropic:
|
| beta = <functools.cached_property object>
| close(self) -> 'None' from anthropic._client.Anthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.Anthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic.Anthropic:
|
| auth_headers
|
| custom_auth
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic.Anthropic:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| __orig_bases__ = (anthropic._base_client.BaseClient[httpx.Client, anth...
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AnthropicBedrock
Python Library Documentation: class AnthropicBedrock in module anthropic.lib.bedrock._client
class AnthropicBedrock(BaseBedrockClient, anthropic._base_client.SyncAPIClient)
| AnthropicBedrock(aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AnthropicBedrock
| BaseBedrockClient
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| copy(self, *, aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self'
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'beta': 'Beta', 'completions': 'Completions', 'mess...
|
| __orig_bases__ = (anthropic.lib.bedrock._client.BaseBedrockClient[http...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| close(self) -> 'None'
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| qs
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AnthropicBedrockMantle
Python Library Documentation: class AnthropicBedrockMantle in module anthropic.lib.bedrock._mantle
class AnthropicBedrockMantle(BaseMantleClient, anthropic._base_client.SyncAPIClient)
| AnthropicBedrockMantle(*, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, api_key: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AnthropicBedrockMantle
| BaseMantleClient
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, api_key: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self'
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_use_sigv4': 'bool', 'aws_access_key': 'str | None...
|
| __orig_bases__ = (anthropic.lib.bedrock._mantle.BaseMantleClient[httpx...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| close(self) -> 'None'
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| custom_auth
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AnthropicError
Python Library Documentation: class AnthropicError in module anthropic
class AnthropicError(builtins.Exception)
| Method resolution order:
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.Exception:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.AnthropicFoundry
Python Library Documentation: class AnthropicFoundry in module anthropic.lib.foundry
class AnthropicFoundry(BaseFoundryClient, anthropic.Anthropic)
| AnthropicFoundry(*, resource: 'str | None' = None, api_key: 'str | None' = None, azure_ad_token_provider: 'AzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AnthropicFoundry
| BaseFoundryClient
| anthropic.Anthropic
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, resource: 'str | None' = None, api_key: 'str | None' = None, azure_ad_token_provider: 'AzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Construct a new synchronous Anthropic Foundry client instance.
|
| This automatically infers the following arguments from their corresponding environment variables if they are not provided:
| - `api_key` from `ANTHROPIC_FOUNDRY_API_KEY`
| - `resource` from `ANTHROPIC_FOUNDRY_RESOURCE`
| - `base_url` from `ANTHROPIC_FOUNDRY_BASE_URL`
|
| Args:
| resource: Your Foundry resource name, e.g. `example-resource` for `https://example-resource.services.ai.azure.com/anthropic/`
| azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request.
|
| beta = <functools.cached_property object>
| Return beta resource instance with excluded unsupported endpoints.
|
| copy(self, *, api_key: 'str | None' = None, azure_ad_token_provider: 'AzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| messages = <functools.cached_property object>
| Return messages resource instance with excluded unsupported endpoints.
|
| models = <functools.cached_property object>
| Models endpoint is not supported for Anthropic Foundry client.
|
| with_options = copy(self, *, api_key: 'str | None' = None, azure_ad_token_provider: 'AzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (anthropic.lib.foundry.BaseFoundryClient[httpx.Client...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.Anthropic:
|
| close(self) -> 'None' from anthropic._client.Anthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.Anthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic.Anthropic:
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic.Anthropic:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AnthropicGoogleCloud
Python Library Documentation: class AnthropicGoogleCloud in module anthropic.lib.google_cloud._client
class AnthropicGoogleCloud(BaseGoogleCloudClient, anthropic.Anthropic)
| AnthropicGoogleCloud(*, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None' = None, token_provider: 'TokenProvider | None' = None, credentials: 'GoogleCredentials | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Synchronous client for the first-party Anthropic API served through Google's
| gateway (Claude Platform on Google Cloud).
|
| The whole first-party surface is proxied verbatim (no URL or body rewriting), so
| this subclasses the full ``Anthropic`` client. Authentication is a GCP bearer
| token; the deprecated Completions endpoint is not exposed.
|
| Method resolution order:
| AnthropicGoogleCloud
| BaseGoogleCloudClient
| anthropic.Anthropic
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None' = None, token_provider: 'TokenProvider | None' = None, credentials: 'GoogleCredentials | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Construct a new synchronous Claude Platform on Google Cloud client.
|
| Auth precedence (first match wins, unless ``skip_auth=True``):
| 1. ``token_provider`` — a callable returning a GCP access token, invoked per request.
| 2. ``credentials`` — a ``google.auth`` Credentials object, refreshed as needed.
| 3. Application Default Credentials (``google.auth.default``).
|
| Args:
| project: GCP consumer project id (or ``ANTHROPIC_GOOGLE_CLOUD_PROJECT``,
| else ``GOOGLE_CLOUD_PROJECT``). Only needed when the base URL must be
| derived; if omitted there, it is taken from an explicit ``credentials``
| object when it exposes one, or back-filled from ADC on the first request.
| location: GCP location (or ``ANTHROPIC_GOOGLE_CLOUD_LOCATION``). Optional —
| defaults to ``global``, the region the gateway should normally be
| addressed through.
| workspace_id: The Anthropic workspace ID (or ``ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID``).
| Required unless ``skip_auth`` is set with an explicit ``base_url``.
| skip_auth: For pre-authenticated proxies — skips token attachment. A
| workspace ID is still needed to derive the base URL; pass ``base_url``
| to construct without one. Mutually exclusive with the credential
| arguments.
|
| completions = <functools.cached_property object>
| Completions endpoint is deprecated and not supported for the Google Cloud client.
|
| copy(self, *, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None | NotGiven' = NOT_GIVEN, token_provider: 'TokenProvider | None | NotGiven' = NOT_GIVEN, credentials: 'GoogleCredentials | None | NotGiven' = NOT_GIVEN, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client re-using the current options, with optional overrides.
|
| Passing either of ``token_provider`` / ``credentials`` replaces the
| inherited credential configuration wholesale — the source not passed is
| cleared, so an explicit lower-precedence credential takes effect.
| ``workspace_id=None`` clears the workspace ID; ``project`` /
| ``location`` overrides re-derive a template-derived base URL.
|
| with_options = copy(self, *, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None | NotGiven' = NOT_GIVEN, token_provider: 'TokenProvider | None | NotGiven' = NOT_GIVEN, credentials: 'GoogleCredentials | None | NotGiven' = NOT_GIVEN, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_skip_auth': 'bool', 'workspace_id': 'str | None'}
|
| __orig_bases__ = (anthropic.lib.google_cloud._client.BaseGoogleCloudCl...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseGoogleCloudClient:
|
| google_credentials
| The ``google.auth`` credentials in use (explicit or lazily-loaded ADC), if any.
|
| Distinct from ``.credentials``, which is the base client's first-party
| credentials provider and is always ``None`` on this client.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseGoogleCloudClient:
|
| base_url
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.Anthropic:
|
| beta = <functools.cached_property object>
| close(self) -> 'None' from anthropic._client.Anthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.Anthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic.Anthropic:
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic.Anthropic:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AnthropicVertex
Python Library Documentation: class AnthropicVertex in module anthropic.lib.vertex._client
class AnthropicVertex(BaseVertexClient, anthropic._base_client.SyncAPIClient)
| AnthropicVertex(*, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AnthropicVertex
| BaseVertexClient
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| copy(self, *, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self'
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'beta': 'Beta', 'messages': 'Messages'}
|
| __orig_bases__ = (anthropic.lib.vertex._client.BaseVertexClient[httpx....
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from BaseVertexClient:
|
| project_id = <functools.cached_property object>
| region = <functools.cached_property object>
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| close(self) -> 'None'
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| qs
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAPIResponse
Python Library Documentation: class AsyncAPIResponse in module anthropic._response
class AsyncAPIResponse(BaseAPIResponse)
| AsyncAPIResponse(*, raw: 'httpx.Response', cast_to: 'type[R]', client: 'BaseClient[Any, Any]', stream: 'bool', stream_cls: 'type[Stream[Any]] | type[AsyncStream[Any]] | None', options: 'FinalRequestOptions', retries_taken: 'int' = 0) -> 'None'
|
| Method resolution order:
| AsyncAPIResponse
| BaseAPIResponse
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| async close(self) -> 'None'
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| async iter_bytes(self, chunk_size: 'int | None' = None) -> 'AsyncIterator[bytes]'
| A byte-iterator over the decoded response content.
|
| This automatically handles gzip, deflate and brotli encoded responses.
|
| async iter_lines(self) -> 'AsyncIterator[str]'
| Like `iter_text()` but will only yield chunks for each line
|
| async iter_text(self, chunk_size: 'int | None' = None) -> 'AsyncIterator[str]'
| A str-iterator over the decoded response content
| that handles both gzip, deflate, etc but also detects the content's
| string encoding.
|
| async json(self) -> 'object'
| Read and decode the JSON response content.
|
| async parse(self, *, to: 'type[_T] | None' = None) -> 'R | _T'
| Returns the rich python representation of this response's data.
|
| For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
|
| You can customise the type that the response is parsed into through
| the `to` argument, e.g.
|
| ```py
| from anthropic import BaseModel
|
|
| class MyModel(BaseModel):
| foo: str
|
|
| obj = response.parse(to=MyModel)
| print(obj.foo)
| ```
|
| We support parsing:
| - `BaseModel`
| - `dict`
| - `list`
| - `Union`
| - `str`
| - `httpx.Response`
|
| async read(self) -> 'bytes'
| Read and return the binary response content.
|
| async text(self) -> 'str'
| Read and decode the response content into a string.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| request_id
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (anthropic._response.BaseAPIResponse[~R],)
|
| __parameters__ = (~R,)
|
| ----------------------------------------------------------------------
| Methods inherited from BaseAPIResponse:
|
| __init__(self, *, raw: 'httpx.Response', cast_to: 'type[R]', client: 'BaseClient[Any, Any]', stream: 'bool', stream_cls: 'type[Stream[Any]] | type[AsyncStream[Any]] | None', options: 'FinalRequestOptions', retries_taken: 'int' = 0) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseAPIResponse:
|
| elapsed
| The time taken for the complete request/response cycle to complete.
|
| headers
|
| http_request
| Returns the httpx Request instance associated with the current response.
|
| http_version
|
| is_closed
| Whether or not the response body has been closed.
|
| If this is False then there is response data that has not been read yet.
| You must either fully consume the response body or call `.close()`
| before discarding the response to prevent resource leaks.
|
| method
|
| status_code
|
| url
| Returns the URL for which the request was made.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseAPIResponse:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAnthropic
Python Library Documentation: class AsyncAnthropic in module anthropic
class AsyncAnthropic(anthropic._base_client.AsyncAPIClient)
| AsyncAnthropic(*, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None'
|
| Method resolution order:
| AsyncAnthropic
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None' from anthropic._client.AsyncAnthropic
| Construct a new async AsyncAnthropic client instance.
|
| Credentials are resolved in the following order (first match wins):
|
| 1. Explicit constructor arguments — ``api_key=``, ``auth_token=``,
| ``credentials=``, ``config=``, or ``profile=``. When any of these
| is passed, environment variables are not consulted for credentials.
| 2. ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` environment
| variables.
| 3. ``ANTHROPIC_PROFILE`` environment variable — loads the named
| profile from ``<config_dir>/configs/<profile>.json``.
| 4. Workload identity federation environment variables —
| ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` +
| ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID``.
| 5. The active profile on disk — the profile named by
| ``<config_dir>/active_config``, or ``default``.
|
| ``credentials=``, ``config=``, and ``profile=`` are mutually exclusive.
|
| If a static credential is supplied alongside a credentials provider
| (``credentials=`` / ``config=`` / ``profile=``), or if
| ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside a
| profile or federation configuration, the static credential takes
| precedence and a one-shot warning is logged on the ``anthropic``
| logger.
|
| beta = <functools.cached_property object>
| async close(self) -> 'None' from anthropic._client.AsyncAnthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self' from anthropic._client.AsyncAnthropic
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.AsyncAnthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| __annotations__ = {'_custom_auth': 'AccessTokenAuth | None', '_token_c...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| __orig_bases__ = (anthropic._base_client.BaseClient[httpx.AsyncClient,...
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAnthropicAWS
Python Library Documentation: class AsyncAnthropicAWS in module anthropic.lib.aws._client
class AsyncAnthropicAWS(anthropic.AsyncAnthropic)
| AsyncAnthropicAWS(*, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, auth_token: 'str | None' = None, webhook_key: 'str | None' = None) -> 'None'
|
| Method resolution order:
| AsyncAnthropicAWS
| anthropic.AsyncAnthropic
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, auth_token: 'str | None' = None, webhook_key: 'str | None' = None) -> 'None'
| Construct a new async AsyncAnthropic client instance.
|
| Credentials are resolved in the following order (first match wins):
|
| 1. Explicit constructor arguments — ``api_key=``, ``auth_token=``,
| ``credentials=``, ``config=``, or ``profile=``. When any of these
| is passed, environment variables are not consulted for credentials.
| 2. ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` environment
| variables.
| 3. ``ANTHROPIC_PROFILE`` environment variable — loads the named
| profile from ``<config_dir>/configs/<profile>.json``.
| 4. Workload identity federation environment variables —
| ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` +
| ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID``.
| 5. The active profile on disk — the profile named by
| ``<config_dir>/active_config``, or ``default``.
|
| ``credentials=``, ``config=``, and ``profile=`` are mutually exclusive.
|
| If a static credential is supplied alongside a credentials provider
| (``credentials=`` / ``config=`` / ``profile=``), or if
| ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside a
| profile or federation configuration, the static credential takes
| precedence and a one-shot warning is logged on the ``anthropic``
| logger.
|
| copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_options = copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, workspace_id: 'str | None' = None, skip_auth: 'bool | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| default_headers
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_skip_auth': 'bool', '_use_sigv4': 'bool', 'aws_ac...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.AsyncAnthropic:
|
| beta = <functools.cached_property object>
| async close(self) -> 'None' from anthropic._client.AsyncAnthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.AsyncAnthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic.AsyncAnthropic:
|
| auth_headers
|
| custom_auth
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic.AsyncAnthropic:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| __orig_bases__ = (anthropic._base_client.BaseClient[httpx.AsyncClient,...
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAnthropicBedrock
Python Library Documentation: class AsyncAnthropicBedrock in module anthropic.lib.bedrock._client
class AsyncAnthropicBedrock(BaseBedrockClient, anthropic._base_client.AsyncAPIClient)
| AsyncAnthropicBedrock(aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AsyncAnthropicBedrock
| BaseBedrockClient
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| copy(self, *, aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self'
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, aws_secret_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_region: 'str | None' = None, aws_session_token: 'str | None' = None, api_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'beta': 'AsyncBeta', 'completions': 'AsyncCompletio...
|
| __orig_bases__ = (anthropic.lib.bedrock._client.BaseBedrockClient[...x...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async close(self) -> 'None'
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| qs
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAnthropicBedrockMantle
Python Library Documentation: class AsyncAnthropicBedrockMantle in module anthropic.lib.bedrock._mantle
class AsyncAnthropicBedrockMantle(BaseMantleClient, anthropic._base_client.AsyncAPIClient)
| AsyncAnthropicBedrockMantle(*, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, api_key: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AsyncAnthropicBedrockMantle
| BaseMantleClient
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, api_key: 'str | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self'
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, api_key: 'str | None' = None, aws_access_key: 'str | None' = None, aws_secret_key: 'str | None' = None, aws_session_token: 'str | None' = None, aws_region: 'str | None' = None, aws_profile: 'str | None' = None, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_use_sigv4': 'bool', 'aws_access_key': 'str | None...
|
| __orig_bases__ = (anthropic.lib.bedrock._mantle.BaseMantleClient[httpx...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async close(self) -> 'None'
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| custom_auth
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAnthropicFoundry
Python Library Documentation: class AsyncAnthropicFoundry in module anthropic.lib.foundry
class AsyncAnthropicFoundry(BaseFoundryClient, anthropic.AsyncAnthropic)
| AsyncAnthropicFoundry(*, resource: 'str | None' = None, api_key: 'str | None' = None, azure_ad_token_provider: 'AsyncAzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AsyncAnthropicFoundry
| BaseFoundryClient
| anthropic.AsyncAnthropic
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, resource: 'str | None' = None, api_key: 'str | None' = None, azure_ad_token_provider: 'AsyncAzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Construct a new asynchronous Anthropic Foundry client instance.
|
| This automatically infers the following arguments from their corresponding environment variables if they are not provided:
| - `api_key` from `ANTHROPIC_FOUNDRY_API_KEY`
| - `resource` from `ANTHROPIC_FOUNDRY_RESOURCE`
| - `base_url` from `ANTHROPIC_FOUNDRY_BASE_URL`
|
| Args:
| resource: Your Foundry resource name, e.g. `example-resource` for `https://example-resource.services.ai.azure.com/anthropic/`
| azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request.
|
| beta = <functools.cached_property object>
| Return beta resource instance with excluded unsupported endpoints.
|
| copy(self, *, api_key: 'str | None' = None, azure_ad_token_provider: 'AsyncAzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| messages = <functools.cached_property object>
| Return messages resource instance with excluded unsupported endpoints.
|
| models = <functools.cached_property object>
| Models endpoint is not supported for Azure Anthropic client.
|
| with_options = copy(self, *, api_key: 'str | None' = None, azure_ad_token_provider: 'AsyncAzureADTokenProvider | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (anthropic.lib.foundry.BaseFoundryClient[httpx.AsyncC...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.AsyncAnthropic:
|
| async close(self) -> 'None' from anthropic._client.AsyncAnthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.AsyncAnthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic.AsyncAnthropic:
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic.AsyncAnthropic:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAnthropicGoogleCloud
Python Library Documentation: class AsyncAnthropicGoogleCloud in module anthropic.lib.google_cloud._client
class AsyncAnthropicGoogleCloud(BaseGoogleCloudClient, anthropic.AsyncAnthropic)
| AsyncAnthropicGoogleCloud(*, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None' = None, token_provider: 'AsyncTokenProvider | None' = None, credentials: 'GoogleCredentials | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Asynchronous client for the first-party Anthropic API served through Google's
| gateway (Claude Platform on Google Cloud). See ``AnthropicGoogleCloud``.
|
| Method resolution order:
| AsyncAnthropicGoogleCloud
| BaseGoogleCloudClient
| anthropic.AsyncAnthropic
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None' = None, token_provider: 'AsyncTokenProvider | None' = None, credentials: 'GoogleCredentials | None' = None, skip_auth: 'bool' = False, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Construct a new asynchronous Claude Platform on Google Cloud client.
|
| ``token_provider`` may be sync or async; sync providers are run off the
| event loop. See ``AnthropicGoogleCloud`` for the full argument and
| auth-precedence docs.
|
| completions = <functools.cached_property object>
| Completions endpoint is deprecated and not supported for the Google Cloud client.
|
| copy(self, *, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None | NotGiven' = NOT_GIVEN, token_provider: 'AsyncTokenProvider | None | NotGiven' = NOT_GIVEN, credentials: 'GoogleCredentials | None | NotGiven' = NOT_GIVEN, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client re-using the current options, with optional overrides.
|
| See ``AnthropicGoogleCloud.copy`` for the override semantics.
|
| with_options = copy(self, *, project: 'str | None' = None, location: 'str | None' = None, workspace_id: 'str | None | NotGiven' = NOT_GIVEN, token_provider: 'AsyncTokenProvider | None | NotGiven' = NOT_GIVEN, credentials: 'GoogleCredentials | None | NotGiven' = NOT_GIVEN, skip_auth: 'bool | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_skip_auth': 'bool', 'workspace_id': 'str | None'}
|
| __orig_bases__ = (anthropic.lib.google_cloud._client.BaseGoogleClo...x...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseGoogleCloudClient:
|
| google_credentials
| The ``google.auth`` credentials in use (explicit or lazily-loaded ADC), if any.
|
| Distinct from ``.credentials``, which is the base client's first-party
| credentials provider and is always ``None`` on this client.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseGoogleCloudClient:
|
| base_url
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.AsyncAnthropic:
|
| beta = <functools.cached_property object>
| async close(self) -> 'None' from anthropic._client.AsyncAnthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.AsyncAnthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic.AsyncAnthropic:
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic.AsyncAnthropic:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncAnthropicVertex
Python Library Documentation: class AsyncAnthropicVertex in module anthropic.lib.vertex._client
class AsyncAnthropicVertex(BaseVertexClient, anthropic._base_client.AsyncAPIClient)
| AsyncAnthropicVertex(*, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
|
| Method resolution order:
| AsyncAnthropicVertex
| BaseVertexClient
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| copy(self, *, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self'
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, region: 'str | NotGiven' = NOT_GIVEN, project_id: 'str | NotGiven' = NOT_GIVEN, access_token: 'str | None' = None, credentials: 'GoogleCredentials | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'beta': 'AsyncBeta', 'messages': 'AsyncMessages'}
|
| __orig_bases__ = (anthropic.lib.vertex._client.BaseVertexClient[httpx....
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from BaseVertexClient:
|
| project_id = <functools.cached_property object>
| region = <functools.cached_property object>
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async close(self) -> 'None'
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| qs
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncCallNext
Python Library Documentation: _CallableGenericAlias in module anthropic
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
anthropic.AsyncClient
Python Library Documentation: class AsyncAnthropic in module anthropic
class AsyncAnthropic(anthropic._base_client.AsyncAPIClient)
| AsyncAnthropic(*, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None'
|
| Method resolution order:
| AsyncAnthropic
| anthropic._base_client.AsyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.AsyncClient | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None' from anthropic._client.AsyncAnthropic
| Construct a new async AsyncAnthropic client instance.
|
| Credentials are resolved in the following order (first match wins):
|
| 1. Explicit constructor arguments — ``api_key=``, ``auth_token=``,
| ``credentials=``, ``config=``, or ``profile=``. When any of these
| is passed, environment variables are not consulted for credentials.
| 2. ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` environment
| variables.
| 3. ``ANTHROPIC_PROFILE`` environment variable — loads the named
| profile from ``<config_dir>/configs/<profile>.json``.
| 4. Workload identity federation environment variables —
| ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` +
| ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID``.
| 5. The active profile on disk — the profile named by
| ``<config_dir>/active_config``, or ``default``.
|
| ``credentials=``, ``config=``, and ``profile=`` are mutually exclusive.
|
| If a static credential is supplied alongside a credentials provider
| (``credentials=`` / ``config=`` / ``profile=``), or if
| ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside a
| profile or federation configuration, the static credential takes
| precedence and a one-shot warning is logged on the ``anthropic``
| logger.
|
| beta = <functools.cached_property object>
| async close(self) -> 'None' from anthropic._client.AsyncAnthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self' from anthropic._client.AsyncAnthropic
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.AsyncAnthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.AsyncClient | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| __annotations__ = {'_custom_auth': 'AccessTokenAuth | None', '_token_c...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.AsyncAPIClient:
|
| async __aenter__(self: '_T') -> '_T'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[_T]', page: 'Type[AsyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'AsyncPaginator[_T, AsyncPageT]'
|
| is_closed(self) -> 'bool'
|
| async patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| async put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'AsyncBinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| async request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_AsyncStreamT] | None' = None) -> 'ResponseT | _AsyncStreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.AsyncAPIClient:
|
| __orig_bases__ = (anthropic._base_client.BaseClient[httpx.AsyncClient,...
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncMessageStream
Python Library Documentation: class AsyncMessageStream in module anthropic.lib.streaming._messages
class AsyncMessageStream(typing.Generic)
| AsyncMessageStream(raw_stream: 'AsyncStream[RawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
|
| Method resolution order:
| AsyncMessageStream
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| async __aenter__(self) -> 'Self'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async __aiter__(self) -> 'AsyncIterator[ParsedMessageStreamEvent[ResponseFormatT]]'
|
| async __anext__(self) -> 'ParsedMessageStreamEvent[ResponseFormatT]'
|
| __init__(self, raw_stream: 'AsyncStream[RawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| async __stream__(self) -> 'AsyncIterator[ParsedMessageStreamEvent[ResponseFormatT]]'
|
| async __stream_text__(self) -> 'AsyncIterator[str]'
|
| async close(self) -> 'None'
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| async get_final_message(self) -> 'ParsedMessage[ResponseFormatT]'
| Waits until the stream has been read to completion and returns
| the accumulated `Message` object.
|
| async get_final_text(self) -> 'str'
| Returns all `text` content blocks concatenated together.
|
| > [!NOTE]
| > Currently the API will only respond with a single content block.
|
| Will raise an error if no `text` content blocks were returned.
|
| async until_done(self) -> 'None'
| Waits until the stream has been consumed
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| current_message_snapshot
|
| request_id
|
| response
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'text_stream': 'AsyncIterator[str]'}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncMessageStreamManager
Python Library Documentation: class AsyncMessageStreamManager in module anthropic.lib.streaming._messages
class AsyncMessageStreamManager(typing.Generic)
| AsyncMessageStreamManager(api_request: 'Awaitable[AsyncStream[RawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven' = NOT_GIVEN) -> 'None'
|
| Wrapper over AsyncMessageStream that is returned by `.stream()`
| so that an async context manager can be used without `await`ing the
| original client call.
|
| ```py
| async with client.messages.stream(...) as stream:
| async for chunk in stream:
| ...
| ```
|
| Method resolution order:
| AsyncMessageStreamManager
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| async __aenter__(self) -> 'AsyncMessageStream[ResponseFormatT]'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| __init__(self, api_request: 'Awaitable[AsyncStream[RawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven' = NOT_GIVEN) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AsyncMiddlewareCallable
Python Library Documentation: _CallableGenericAlias in module anthropic
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
anthropic.AsyncStream
Python Library Documentation: class AsyncStream in module anthropic
class AsyncStream(typing.Generic)
| AsyncStream(*, cast_to: 'type[_T]', response: 'httpx.Response', client: 'AsyncAnthropic', options: 'Optional[FinalRequestOptions]' = None) -> 'None'
|
| Provides the core interface to iterate over an asynchronous stream response.
|
| Method resolution order:
| AsyncStream
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| async __aenter__(self) -> 'Self' from anthropic._streaming.AsyncStream
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None' from anthropic._streaming.AsyncStream
|
| async __aiter__(self) -> 'AsyncIterator[_T]' from anthropic._streaming.AsyncStream
|
| async __anext__(self) -> '_T' from anthropic._streaming.AsyncStream
|
| __init__(self, *, cast_to: 'type[_T]', response: 'httpx.Response', client: 'AsyncAnthropic', options: 'Optional[FinalRequestOptions]' = None) -> 'None' from anthropic._streaming.AsyncStream
| Initialize self. See help(type(self)) for accurate signature.
|
| async __stream__(self) -> 'AsyncIterator[_T]' from anthropic._streaming.AsyncStream
|
| async close(self) -> 'None' from anthropic._streaming.AsyncStream
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| raw_events(response: 'httpx.Response') -> 'AsyncIterator[ServerSentEvent]' from anthropic._streaming.AsyncStream
| Iterate the raw Server-Sent Events from `response`, before any JSON
| parsing or event-name filtering.
|
| This reads the response body directly, so the response is consumed.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'_decoder': 'SSEDecoder | SSEBytesDecoder', '_optio...
|
| __orig_bases__ = (typing.Generic[~_T],)
|
| __parameters__ = (~_T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.AuthenticationError
Python Library Documentation: class AuthenticationError in module anthropic
class AuthenticationError(APIStatusError)
| AuthenticationError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| AuthenticationError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[401]'}
|
| status_code = 401
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.BadRequestError
Python Library Documentation: class BadRequestError in module anthropic
class BadRequestError(APIStatusError)
| BadRequestError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| BadRequestError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[400]'}
|
| status_code = 400
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.BaseModel
Python Library Documentation: class BaseModel in module anthropic
class BaseModel(pydantic.main.BaseModel)
| BaseModel(**data: 'Any') -> 'None'
|
| Method resolution order:
| BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Methods defined here:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'model_config': 'ClassVar[ConfigDict]'}
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.BaseModel'>, 'con...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {}
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="BaseModel", validator=...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {}
anthropic.BetaAsyncMessageStream
Python Library Documentation: class BetaAsyncMessageStream in module anthropic.lib.streaming._beta_messages
class BetaAsyncMessageStream(typing.Generic)
| BetaAsyncMessageStream(raw_stream: 'AsyncStream[BetaRawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
|
| Method resolution order:
| BetaAsyncMessageStream
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| async __aenter__(self) -> 'Self'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| async __aiter__(self) -> 'AsyncIterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]'
|
| async __anext__(self) -> 'ParsedBetaMessageStreamEvent[ResponseFormatT]'
|
| __init__(self, raw_stream: 'AsyncStream[BetaRawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| async __stream__(self) -> 'AsyncIterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]'
|
| async __stream_text__(self) -> 'AsyncIterator[str]'
|
| async close(self) -> 'None'
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| async get_final_message(self) -> 'ParsedBetaMessage[ResponseFormatT]'
| Waits until the stream has been read to completion and returns
| the accumulated `Message` object.
|
| async get_final_text(self) -> 'str'
| Returns all `text` content blocks concatenated together.
|
| > [!NOTE]
| > Currently the API will only respond with a single content block.
|
| Will raise an error if no `text` content blocks were returned.
|
| async until_done(self) -> 'None'
| Waits until the stream has been consumed
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| current_message_snapshot
|
| request_id
|
| response
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'text_stream': 'AsyncIterator[str]'}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.BetaAsyncMessageStreamManager
Python Library Documentation: class BetaAsyncMessageStreamManager in module anthropic.lib.streaming._beta_messages
class BetaAsyncMessageStreamManager(typing.Generic)
| BetaAsyncMessageStreamManager(api_request: 'Awaitable[AsyncStream[BetaRawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven' = NOT_GIVEN) -> 'None'
|
| Wrapper over BetaAsyncMessageStream that is returned by `.stream()`
| so that an async context manager can be used without `await`ing the
| original client call.
|
| ```py
| async with client.beta.messages.stream(...) as stream:
| async for chunk in stream:
| ...
| ```
|
| Method resolution order:
| BetaAsyncMessageStreamManager
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| async __aenter__(self) -> 'BetaAsyncMessageStream[ResponseFormatT]'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| __init__(self, api_request: 'Awaitable[AsyncStream[BetaRawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven' = NOT_GIVEN) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.BetaContentBlockStopEvent
Python Library Documentation: class ParsedBetaContentBlockStopEvent[object] in module anthropic.lib.streaming._beta_types
class ParsedBetaContentBlockStopEvent[object](ParsedBetaContentBlockStopEvent)
| ParsedBetaContentBlockStopEvent[object](*, index: int, type: Literal['content_block_stop'], content_block: Annotated[Union[anthropic.types.beta.parsed_beta_message.ParsedBetaTextBlock, anthropic.types.beta.beta_thinking_block.BetaThinkingBlock, anthropic.types.beta.beta_redacted_thinking_block.BetaRedactedThinkingBlock, anthropic.types.beta.beta_tool_use_block.BetaToolUseBlock, anthropic.types.beta.beta_server_tool_use_block.BetaServerToolUseBlock, anthropic.types.beta.beta_web_search_tool_result_block.BetaWebSearchToolResultBlock, anthropic.types.beta.beta_web_fetch_tool_result_block.BetaWebFetchToolResultBlock, anthropic.types.beta.beta_advisor_tool_result_block.BetaAdvisorToolResultBlock, anthropic.types.beta.beta_code_execution_tool_result_block.BetaCodeExecutionToolResultBlock, anthropic.types.beta.beta_bash_code_execution_tool_result_block.BetaBashCodeExecutionToolResultBlock, anthropic.types.beta.beta_text_editor_code_execution_tool_result_block.BetaTextEditorCodeExecutionToolResultBlock, anthropic.types.beta.beta_tool_search_tool_result_block.BetaToolSearchToolResultBlock, anthropic.types.beta.beta_mcp_tool_use_block.BetaMCPToolUseBlock, anthropic.types.beta.beta_mcp_tool_result_block.BetaMCPToolResultBlock, anthropic.types.beta.beta_container_upload_block.BetaContainerUploadBlock, anthropic.types.beta.beta_compaction_block.BetaCompactionBlock, anthropic.types.beta.beta_fallback_block.BetaFallbackBlock], PropertyInfo(alias='None', format=None, format_template='None', discriminator='type')], **extra_data: Any) -> None
|
| Method resolution order:
| ParsedBetaContentBlockStopEvent[object]
| ParsedBetaContentBlockStopEvent
| anthropic.types.beta.beta_raw_content_block_stop_event.BetaRawContentBlockStopEvent
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __class_vars__ = set()
|
| __parameters__ = ()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'content_block': FieldInfo(annotation=Union[Par...
|
| __pydantic_generic_metadata__ = {'args': (<class 'object'>,), 'origin'...
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedBetaContentBlock...
|
| __signature__ = <Signature (*, index: int, type: Literal['conten...scr...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from ParsedBetaContentBlockStopEvent:
|
| __orig_bases__ = (<class 'anthropic.types.beta.beta_raw_content_block_...
|
| __pydantic_parent_namespace__ = None
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'content_block': FieldInfo(annotation=Union[ParsedBeta...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.BetaFallbackState
Python Library Documentation: class BetaFallbackState in module anthropic
class BetaFallbackState(builtins.object)
| BetaFallbackState() -> 'None'
|
| Tracks which fallback a sequence of requests is pinned to.
|
| Create one and enter it (`with state:` — the same context manager works for
| both clients) around every request that should share the pin — the turns of
| one conversation, or any wider scope the stickiness should apply to;
| `BetaRefusalFallbackMiddleware` mutates it in place when a model refuses.
|
| Methods defined here:
|
| __enter__(self) -> 'BetaFallbackState' from anthropic.lib.middleware._fallbacks.BetaFallbackState
|
| __exit__(self, *exc_info: 'object') -> 'None' from anthropic.lib.middleware._fallbacks.BetaFallbackState
|
| __init__(self) -> 'None' from anthropic.lib.middleware._fallbacks.BetaFallbackState
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'index': 'int | None'}
anthropic.BetaInputJsonEvent
Python Library Documentation: class BetaInputJsonEvent in module anthropic.lib.streaming._beta_types
class BetaInputJsonEvent(anthropic.BaseModel)
| BetaInputJsonEvent(**extra_data: Any) -> None
|
| Method resolution order:
| BetaInputJsonEvent
| anthropic.BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'partial_json': <class 'str'>, 'snapshot': <class '...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.lib.streaming._be...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'partial_json': FieldInfo(annotation=str, requi...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="BetaInputJsonEvent", v...
|
| __signature__ = <Signature (*, type: Literal['input_json'], part...tr,...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.BaseModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'partial_json': FieldInfo(annotation=str, required=Tru...
anthropic.BetaMessageStopEvent
Python Library Documentation: class ParsedBetaMessageStopEvent[object] in module anthropic.lib.streaming._beta_types
class ParsedBetaMessageStopEvent[object](ParsedBetaMessageStopEvent)
| ParsedBetaMessageStopEvent[object](*, type: Literal['message_stop'], message: anthropic.types.beta.parsed_beta_message.ParsedBetaMessage[TypeVar], **extra_data: Any) -> None
|
| Method resolution order:
| ParsedBetaMessageStopEvent[object]
| ParsedBetaMessageStopEvent
| anthropic.types.beta.beta_raw_message_stop_event.BetaRawMessageStopEvent
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __class_vars__ = set()
|
| __parameters__ = ()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'message': FieldInfo(annotation=ParsedBetaMessa...
|
| __pydantic_generic_metadata__ = {'args': (<class 'object'>,), 'origin'...
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedBetaMessageStopE...
|
| __signature__ = <Signature (*, type: Literal['message_stop'], me...dBe...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from ParsedBetaMessageStopEvent:
|
| __orig_bases__ = (<class 'anthropic.types.beta.beta_raw_message_stop_e...
|
| __pydantic_parent_namespace__ = None
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'message': FieldInfo(annotation=ParsedBetaMessage[obje...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.BetaMessageStream
Python Library Documentation: class BetaMessageStream in module anthropic.lib.streaming._beta_messages
class BetaMessageStream(typing.Generic)
| BetaMessageStream(raw_stream: 'Stream[BetaRawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
|
| Method resolution order:
| BetaMessageStream
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'Self'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| __init__(self, raw_stream: 'Stream[BetaRawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> 'Iterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]'
|
| __next__(self) -> 'ParsedBetaMessageStreamEvent[ResponseFormatT]'
|
| __stream__(self) -> 'Iterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]'
|
| __stream_text__(self) -> 'Iterator[str]'
|
| close(self) -> 'None'
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| get_final_message(self) -> 'ParsedBetaMessage[ResponseFormatT]'
| Waits until the stream has been read to completion and returns
| the accumulated `Message` object.
|
| get_final_text(self) -> 'str'
| Returns all `text` content blocks concatenated together.
|
| > [!NOTE]
| > Currently the API will only respond with a single content block.
|
| Will raise an error if no `text` content blocks were returned.
|
| until_done(self) -> 'None'
| Blocks until the stream has been consumed
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| current_message_snapshot
|
| request_id
|
| response
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'text_stream': 'Iterator[str]'}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.BetaMessageStreamEvent
Python Library Documentation: _AnnotatedAlias in module typing Annotated = typing.Union[anthropic.lib.streaming._beta_types...ming._beta_types.ParsedBetaContentBlockStopEvent]
anthropic.BetaMessageStreamManager
Python Library Documentation: class BetaMessageStreamManager in module anthropic.lib.streaming._beta_messages
class BetaMessageStreamManager(typing.Generic)
| BetaMessageStreamManager(api_request: 'Callable[[], Stream[BetaRawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven') -> 'None'
|
| Wrapper over MessageStream that is returned by `.stream()`.
|
| ```py
| with client.beta.messages.stream(...) as stream:
| for chunk in stream:
| ...
| ```
|
| Method resolution order:
| BetaMessageStreamManager
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'BetaMessageStream[ResponseFormatT]'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| __init__(self, api_request: 'Callable[[], Stream[BetaRawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.BetaRefusalFallbackMiddleware
Python Library Documentation: class BetaRefusalFallbackMiddleware in module anthropic
class BetaRefusalFallbackMiddleware(Middleware)
| BetaRefusalFallbackMiddleware(fallbacks: 'Iterable[BetaFallbackParam]', *, betas: 'Iterable[AnthropicBetaParam] | None' = None) -> 'None'
|
| Middleware that retries refused beta `/v1/messages` requests down a
| fallback chain, reproducing the server-side `fallbacks` wire shape
| client-side.
|
| Only `client.beta.messages` requests are handled — refusals minted by the
| first-party `client.messages` surface carry no `fallback_credit_token`, so
| those requests pass through untouched.
|
| Each `fallbacks` entry is a patch against the ORIGINAL request params: a
| field set to a value overrides it, a field explicitly `None` unsets it, an
| absent field keeps the original value; `output_config` patches its
| subfields the same way one level deep. Hops never compound — every hop
| patches the original params, never the previous hop's patched request.
|
| Non-streaming: when a response comes back with `stop_reason: "refusal"`, the
| request is retried with each entry of `fallbacks` applied as a patch to the
| original params — passing along the refusal's `fallback_credit_token` (in
| the object form, with `mode: "best_effort"`) when it minted one — until a
| model accepts or the chain is exhausted. A `fallback` seam
| block per model boundary is prepended to the served message's content —
| the same block shape the streaming splice emits. The served hop's `usage`
| is left verbatim (streaming rewrites it to per-hop `usage.iterations`).
|
| Streaming: when the stream ends in `stop_reason: "refusal"`, a second
| request is issued to the fallback model. It carries the refusal's
| `fallback_credit_token`, plus the refused model's partial output as a
| trailing assistant prefill when the refusal grants one
| (`fallback_has_prefill_claim`). The fallback's events are then spliced onto
| the still-open stream, so the client sees one continuous message in the
| server-side `fallbacks` wire shape: a `fallback` content block at each
| model boundary, monotonic block indices, and per-hop `usage.iterations` on
| the final `message_delta`. A refusal before any output streamed retries
| even without a credit token, and the serving hop's `message_start` opens
| the wire carrying the primary's message id.
|
| The fallback-credit beta the credit tokens require is sent by default on
| every request the middleware handles; the `betas` option controls this.
|
| In both modes a fallback that itself refuses with a fresh credit token
| continues down the chain. A streaming fallback whose appended prefill the
| server rejects (HTTP 400 body mismatch) is retried once without it; a
| fallback whose request fails outright is skipped — its token was never
| redeemed, so it carries to the next entry. When every remaining entry fails
| over HTTP, the suppressed refusal is replayed to the client with
| `recommended_model` stamped from the final failure (the failed model for
| capacity errors, `null` otherwise). A refusal surfaced to the client rather
| than retried is reported through the `anthropic.lib.middleware` logger.
|
| To keep later requests on the model that accepted, run them inside a shared
| `BetaFallbackState` context; requests sharing that state start directly at
| the pinned fallback. Reuse one state across whatever scope the pin should
| apply to — typically a conversation. The state is the only pin: `fallback`
| seam blocks replayed in the request history are stripped from the outgoing
| request (an assistant turn left empty by the strip is dropped whole), never
| read back as a pin.
|
| ```py
| client = Anthropic(middleware=[BetaRefusalFallbackMiddleware([{"model": "claude-opus-4-8"}])])
|
| state = BetaFallbackState()
| with state:
| message = client.beta.messages.create(**params)
| ```
|
| Method resolution order:
| BetaRefusalFallbackMiddleware
| Middleware
| builtins.object
|
| Methods defined here:
|
| __init__(self, fallbacks: 'Iterable[BetaFallbackParam]', *, betas: 'Iterable[AnthropicBetaParam] | None' = None) -> 'None' from anthropic.lib.middleware._fallbacks.BetaRefusalFallbackMiddleware
| Args:
| fallbacks: The fallback chain, tried in order. An empty chain disables
| the middleware.
|
| betas: Betas added to the `anthropic-beta` header of every `/v1/messages`
| request this middleware handles — the original request included, since
| refusals only carry a `fallback_credit_token` when the beta is enabled.
| Defaults to `("fallback-credit-2026-07-01",)`; pass `()` to send none.
|
| handle(self, request: 'APIRequest', call_next: 'CallNext') -> 'APIResponse[Any]' from anthropic.lib.middleware._fallbacks.BetaRefusalFallbackMiddleware
|
| async handle_async(self, request: 'APIRequest', call_next: 'AsyncCallNext') -> 'AsyncAPIResponse[Any]' from anthropic.lib.middleware._fallbacks.BetaRefusalFallbackMiddleware
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Middleware:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
anthropic.BetaTextEvent
Python Library Documentation: class ParsedBetaTextEvent in module anthropic.lib.streaming._beta_types
class ParsedBetaTextEvent(anthropic.BaseModel)
| ParsedBetaTextEvent(**extra_data: Any) -> None
|
| Method resolution order:
| ParsedBetaTextEvent
| anthropic.BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Methods defined here:
|
| parsed_snapshot(self) -> Dict[str, Any]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'snapshot': <class 'str'>, 'text': <class 'str'>, '...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.lib.streaming._be...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'snapshot': FieldInfo(annotation=str, required=...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedBetaTextEvent", ...
|
| __signature__ = <Signature (*, type: Literal['text'], text: str, snaps...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.BaseModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'snapshot': FieldInfo(annotation=str, required=True), ...
anthropic.CallNext
Python Library Documentation: _CallableGenericAlias in module anthropic
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
anthropic.Client
Python Library Documentation: class Anthropic in module anthropic
class Anthropic(anthropic._base_client.SyncAPIClient)
| Anthropic(*, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None'
|
| Method resolution order:
| Anthropic
| anthropic._base_client.SyncAPIClient
| anthropic._base_client.BaseClient
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None' = None, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, max_retries: 'int' = 2, default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, http_client: 'httpx.Client | None' = None, middleware: 'Sequence[MiddlewareInput] | None' = None, _strict_response_validation: 'bool' = False, _token_cache: 'TokenCache | None | NotGiven' = NOT_GIVEN) -> 'None' from anthropic._client.Anthropic
| Construct a new synchronous Anthropic client instance.
|
| Credentials are resolved in the following order (first match wins):
|
| 1. Explicit constructor arguments — ``api_key=``, ``auth_token=``,
| ``credentials=``, ``config=``, or ``profile=``. When any of these
| is passed, environment variables are not consulted for credentials.
| 2. ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` environment
| variables.
| 3. ``ANTHROPIC_PROFILE`` environment variable — loads the named
| profile from ``<config_dir>/configs/<profile>.json``.
| 4. Workload identity federation environment variables —
| ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` +
| ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID``.
| 5. The active profile on disk — the profile named by
| ``<config_dir>/active_config``, or ``default``.
|
| ``credentials=``, ``config=``, and ``profile=`` are mutually exclusive.
|
| If a static credential is supplied alongside a credentials provider
| (``credentials=`` / ``config=`` / ``profile=``), or if
| ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside a
| profile or federation configuration, the static credential takes
| precedence and a one-shot warning is logged on the ``anthropic``
| logger.
|
| beta = <functools.cached_property object>
| close(self) -> 'None' from anthropic._client.Anthropic
| Close the underlying HTTPX client.
|
| The client will *not* be usable after this.
|
| completions = <functools.cached_property object>
| copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self' from anthropic._client.Anthropic
| Create a new client instance re-using the same options given to the current client with optional overriding.
|
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| with_middleware(self, *middleware: 'MiddlewareInput') -> 'Self' from anthropic._client.Anthropic
| A new client with the given middleware appended after this client's middleware.
|
| Convenience for applying extra middleware to a single request:
|
| ```py
| client.with_middleware(my_middleware).messages.create(...)
| ```
|
| with_options = copy(self, *, api_key: 'str | None' = None, auth_token: 'str | None' = None, credentials: 'AccessTokenProvider | None | NotGiven' = NOT_GIVEN, config: 'Mapping[str, Any] | None' = None, profile: 'str | None' = None, webhook_key: 'str | None' = None, base_url: 'str | httpx.URL | None' = None, timeout: 'float | Timeout | None | NotGiven' = NOT_GIVEN, http_client: 'httpx.Client | None' = None, max_retries: 'int | NotGiven' = NOT_GIVEN, default_headers: 'Mapping[str, str] | None' = None, set_default_headers: 'Mapping[str, str] | None' = None, default_query: 'Mapping[str, object] | None' = None, set_default_query: 'Mapping[str, object] | None' = None, middleware: 'Sequence[MiddlewareInput] | None | NotGiven' = NOT_GIVEN, _extra_kwargs: 'Mapping[str, Any]' = {}) -> 'Self'
|
| with_raw_response = <functools.cached_property object>
| with_streaming_response = <functools.cached_property object>
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auth_headers
|
| custom_auth
|
| default_headers
|
| qs
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| AI_PROMPT = '\n\nAssistant:'
|
| HUMAN_PROMPT = '\n\nHuman:'
|
| __annotations__ = {'_custom_auth': 'AccessTokenAuth | None', '_token_c...
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.SyncAPIClient:
|
| __enter__(self: '_T') -> '_T'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| delete(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| get(self, path: 'str', *, cast_to: 'Type[ResponseT]', options: 'RequestOptions' = {}, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| get_api_list(self, path: 'str', *, model: 'Type[object]', page: 'Type[SyncPageT]', body: 'Body | None' = None, options: 'RequestOptions' = {}, method: 'str' = 'get') -> 'SyncPageT'
|
| is_closed(self) -> 'bool'
|
| patch(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| post(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, options: 'RequestOptions' = {}, files: 'RequestFiles | None' = None, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| put(self, path: 'str', *, cast_to: 'Type[ResponseT]', body: 'Body | None' = None, content: 'BinaryTypes | None' = None, files: 'RequestFiles | None' = None, options: 'RequestOptions' = {}) -> 'ResponseT'
|
| request(self, cast_to: 'Type[ResponseT]', options: 'FinalRequestOptions', *, stream: 'bool' = False, stream_cls: 'type[_StreamT] | None' = None) -> 'ResponseT | _StreamT'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from anthropic._base_client.SyncAPIClient:
|
| __orig_bases__ = (anthropic._base_client.BaseClient[httpx.Client, anth...
|
| webhook_key = None
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseClient:
|
| platform_headers(self) -> 'Dict[str, str]'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from anthropic._base_client.BaseClient:
|
| default_query
|
| middleware
| The client-level middleware, outermost first.
|
| To run extra middleware for specific calls, derive a client with
| `client.with_options(middleware=[*client.middleware, extra])`.
|
| user_agent
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._base_client.BaseClient:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| base_url
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.ConflictError
Python Library Documentation: class ConflictError in module anthropic
class ConflictError(APIStatusError)
| ConflictError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| ConflictError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[409]'}
|
| status_code = 409
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.ContentBlockStopEvent
Python Library Documentation: class ContentBlockStopEvent in module anthropic.lib.streaming._types
class ContentBlockStopEvent(anthropic.types.raw_content_block_stop_event.RawContentBlockStopEvent)
| ContentBlockStopEvent(**extra_data: Any) -> None
|
| Method resolution order:
| ContentBlockStopEvent
| anthropic.types.raw_content_block_stop_event.RawContentBlockStopEvent
| anthropic.BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'content_block': typing.Annotated[typing.Union[anth...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'content_block': FieldInfo(annotation=Union[Tex...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ContentBlockStopEvent"...
|
| __signature__ = <Signature (*, index: int, type: Literal['conten...scr...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.BaseModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'content_block': FieldInfo(annotation=Union[TextBlock,...
anthropic.CredentialResult
Python Library Documentation: class CredentialResult in module anthropic.lib.credentials._types
class CredentialResult(builtins.object)
| CredentialResult(provider: 'AccessTokenProvider', extra_headers: 'Dict[str, str]' = <factory>, base_url: 'Optional[str]' = None) -> None
|
| Bundles an :class:`AccessTokenProvider` with config-level metadata.
|
| Returned by :func:`default_credentials`. The ``extra_headers`` dict
| carries headers that should be set on every API request (e.g.
| ``anthropic-workspace-id``). The client merges these into its default
| headers at construction time.
|
| ``base_url`` is the API host the resolved profile is configured for
| (e.g. a staging endpoint). The client adopts it as its request
| ``base_url`` *only* when the user did not supply one explicitly via
| the ``base_url=`` kwarg or ``ANTHROPIC_BASE_URL`` — see the
| constructor in ``_client.py``. ``None`` means the profile did not
| specify a host and the client keeps its own default.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, provider: 'AccessTokenProvider', extra_headers: 'Dict[str, str]' = <factory>, base_url: 'Optional[str]' = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'base_url': 'Optional[str]', 'extra_headers': 'Dict...
|
| __dataclass_fields__ = {'base_url': Field(name='base_url',type='Option...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('provider', 'extra_headers', 'base_url')
|
| base_url = None
anthropic.CredentialsFile
Python Library Documentation: class CredentialsFile in module anthropic.lib.credentials._providers class CredentialsFile(builtins.object) | CredentialsFile(profile: 'Optional[str]' = None, *, http_client: 'Optional[httpx.Client]' = None) -> 'None' | | An :class:`AccessTokenProvider` backed by a named profile. | | A profile is a pair of files under the config directory | (``~/.config/anthropic/`` by default; override with ``ANTHROPIC_CONFIG_DIR``): | | * ``configs/<profile>.json`` — non-secret. Holds the nested | ``"authentication"`` object (discriminated by its ``"type"`` field), plus | top-level ``organization_id``, ``workspace_id``, and ``base_url``. | The ``authentication`` object may contain a ``credentials_path`` field | overriding the credentials file location. | * ``credentials/<profile>.json`` — secret (0600). Holds ``access_token``, | ``expires_at``, and (for ``user_oauth`` with a ``client_id``) | ``refresh_token``. | | The split keeps secret material out of files that may need to be readable | by config-only consumers, and lets the SDK enforce 0600 on the credentials | file without locking out config readers. | | Dispatches on the ``authentication.type`` discriminator: | | ``"oidc_federation"`` | OIDC workload identity federation. Lazily constructs a | :class:`WorkloadIdentityCredentials` delegate from the nested auth | fields plus the top-level ``organization_id`` and calls it to perform | the jwt-bearer exchange. | | ``"user_oauth"`` | Output of an interactive PKCE login. If the auth block has a | ``client_id``, performs ``refresh_token`` grants on expiry and | writes the new tokens back to the credentials file (atomic replace, | refresh-token rotation supported). Without a ``client_id``, the | credentials file is treated as externally rotated — the SDK re-reads | it on every invocation and returns whatever ``access_token`` is | there, no refresh grant attempted. This is the pattern for a | sidecar/daemon that mints the access token out-of-band. | | Args: | profile: Profile name. ``None`` resolves via ``ANTHROPIC_PROFILE`` env | → ``<config_dir>/active_config`` pointer file → ``"default"``. | | Methods defined here: | | __call__(self, *, force_refresh: 'bool' = False) -> 'AccessToken' | Call self as a function. | | __init__(self, profile: 'Optional[str]' = None, *, http_client: 'Optional[httpx.Client]' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | bind_base_url(self, base_url: 'str') -> 'None' | Adopt the owning client's ``base_url`` as a fallback for the token | exchange. Slots between the config file's own ``base_url`` field and | the hard-coded default; a ``base_url`` in the config file still wins. | | The owning client binds exactly once at construction; sharing one | instance across clients with different ``base_url`` values is | unsupported and silently picks the last bind when the config file | doesn't pin a host. | | close(self) -> 'None' | Close the owned ``httpx.Client`` if we created one. | | extra_headers(self) -> 'Dict[str, str]' | Return headers derived from the config file (e.g. ``workspace_id``). | | Eagerly reads the config if not yet loaded. The returned dict is | suitable for merging into the client's default headers. | | reload(self) -> 'None' | Drop the cached config so the next call re-reads it from disk. | | ``CredentialsFile`` caches the parsed config across calls to keep the | hot path cheap; a daemon that rotates a profile in place (e.g. flips | ``"type": "user_oauth"`` to ``"type": "oidc_federation"``) will not be | picked up automatically. Callers that need to react to such changes | can call ``reload()`` to force a fresh read on the next ``__call__``. | | ---------------------------------------------------------------------- | Readonly properties defined here: | | config_path | | profile | | resolved_base_url | The ``base_url`` declared in the profile config file, if any. | | Returns ``None`` when the config has no top-level ``base_url`` key — | callers should fall back to their own default rather than the | provider's bound/default value, so a profile that *doesn't* pin a | host never overrides an explicit client setting. Loads the config | on first access. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.DEFAULT_CONNECTION_LIMITS
Python Library Documentation: Limits in module anthropic object class Limits(builtins.object) | Limits(*, max_connections: 'int | None' = None, max_keepalive_connections: 'int | None' = None, keepalive_expiry: 'float | None' = 5.0) -> 'None' | | Configuration for limits to various client behaviors. | | **Parameters:** | | * **max_connections** - The maximum number of concurrent connections that may be | established. | * **max_keepalive_connections** - Allow the connection pool to maintain | keep-alive connections below this point. Should be less than or equal | to `max_connections`. | * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds. | | Methods defined here: | | __eq__(self, other: 'typing.Any') -> 'bool' from httpx._config.Limits | Return self==value. | | __init__(self, *, max_connections: 'int | None' = None, max_keepalive_connections: 'int | None' = None, keepalive_expiry: 'float | None' = 5.0) -> 'None' from httpx._config.Limits | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) -> 'str' from httpx._config.Limits | Return repr(self). | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
anthropic.DEFAULT_MAX_RETRIES
Python Library Documentation: int object
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating-point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Convert to a string according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
|
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is equal to the original int.
|
| The ratio is in lowest terms and has a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_count(self, /)
| Number of ones in the binary representation of the absolute value of self.
|
| Also known as the population count.
|
| >>> bin(13)
| '0b1101'
| >>> (13).bit_count()
| 3
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| is_integer(self, /)
| Returns True. Exists for duck type compatibility with float.is_integer.
|
| to_bytes(self, /, length=1, byteorder='big', *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes. Default
| is length 1.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder='big', *, signed=False)
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
anthropic.DEFAULT_TIMEOUT
Python Library Documentation: Timeout in module anthropic object class Timeout(builtins.object) | Timeout(timeout: 'TimeoutTypes | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, *, connect: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, read: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, write: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, pool: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>) -> 'None' | | Timeout configuration. | | **Usage**: | | Timeout(None) # No timeouts. | Timeout(5.0) # 5s timeout on all operations. | Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. | Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. | Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. | # 5s timeout elsewhere. | | Methods defined here: | | __eq__(self, other: 'typing.Any') -> 'bool' from httpx._config.Timeout | Return self==value. | | __init__(self, timeout: 'TimeoutTypes | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, *, connect: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, read: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, write: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, pool: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>) -> 'None' from httpx._config.Timeout | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) -> 'str' from httpx._config.Timeout | Return repr(self). | | as_dict(self) -> 'dict[str, float | None]' from httpx._config.Timeout | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
anthropic.DefaultAioHttpClient
Python Library Documentation: class _DefaultAioHttpClient in module anthropic class _DefaultAioHttpClient(httpx.AsyncClient) | _DefaultAioHttpClient(**_kwargs: 'Any') -> 'None' | | Method resolution order: | _DefaultAioHttpClient | httpx.AsyncClient | httpx._client.BaseClient | builtins.object | | Methods defined here: | | __init__(self, **_kwargs: 'Any') -> 'None' from anthropic._base_client._DefaultAioHttpClient | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from httpx.AsyncClient: | | async __aenter__(self: 'U') -> 'U' from httpx._client.AsyncClient | | async __aexit__(self, exc_type: 'type[BaseException] | None' = None, exc_value: 'BaseException | None' = None, traceback: 'TracebackType | None' = None) -> 'None' from httpx._client.AsyncClient | | async aclose(self) -> 'None' from httpx._client.AsyncClient | Close transport and proxies. | | async delete(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `DELETE` request. | | **Parameters**: See `httpx.request`. | | async get(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `GET` request. | | **Parameters**: See `httpx.request`. | | async head(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `HEAD` request. | | **Parameters**: See `httpx.request`. | | async options(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send an `OPTIONS` request. | | **Parameters**: See `httpx.request`. | | async patch(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `PATCH` request. | | **Parameters**: See `httpx.request`. | | async post(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `POST` request. | | **Parameters**: See `httpx.request`. | | async put(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `PUT` request. | | **Parameters**: See `httpx.request`. | | async request(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Build and send a request. | | Equivalent to: | | ```python | request = client.build_request(...) | response = await client.send(request, ...) | ``` | | See `AsyncClient.build_request()`, `AsyncClient.send()` | and [Merging of configuration][0] for how the various parameters | are merged with client-level configuration. | | [0]: /advanced/#merging-of-configuration | | async send(self, request: 'Request', *, stream: 'bool' = False, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>) -> 'Response' from httpx._client.AsyncClient | Send a request. | | The request is sent as-is, unmodified. | | Typically you'll want to build one with `AsyncClient.build_request()` | so that any client-level configuration is merged into the request, | but passing an explicit `httpx.Request()` is supported as well. | | See also: [Request instances][0] | | [0]: /advanced/#request-instances | | stream(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'typing.AsyncIterator[Response]' from httpx._client.AsyncClient | Alternative to `httpx.request()` that streams the response body | instead of loading it into memory at once. | | **Parameters**: See `httpx.request`. | | See also: [Streaming Responses][0] | | [0]: /quickstart#streaming-responses | | ---------------------------------------------------------------------- | Methods inherited from httpx._client.BaseClient: | | build_request(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Request' | Build and return a request instance. | | * The `params`, `headers` and `cookies` arguments | are merged with any values set on the client. | * The `url` argument is merged with any `base_url` set on the client. | | See also: [Request instances][0] | | [0]: /advanced/#request-instances | | ---------------------------------------------------------------------- | Readonly properties inherited from httpx._client.BaseClient: | | is_closed | Check if the client being closed | | trust_env | | ---------------------------------------------------------------------- | Data descriptors inherited from httpx._client.BaseClient: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | auth | Authentication class used when none is passed at the request-level. | | See also [Authentication][0]. | | [0]: /quickstart/#authentication | | base_url | Base URL to use when sending requests with relative URLs. | | cookies | Cookie values to include when sending requests. | | event_hooks | | headers | HTTP headers to include when sending requests. | | params | Query parameters to include in the URL when sending requests. | | timeout
anthropic.DefaultAsyncHttpxClient
Python Library Documentation: class _DefaultAsyncHttpxClient in module anthropic class _DefaultAsyncHttpxClient(httpx.AsyncClient) | _DefaultAsyncHttpxClient(**kwargs: 'Any') -> 'None' | | Method resolution order: | _DefaultAsyncHttpxClient | httpx.AsyncClient | httpx._client.BaseClient | builtins.object | | Methods defined here: | | __init__(self, **kwargs: 'Any') -> 'None' from anthropic._base_client._DefaultAsyncHttpxClient | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from httpx.AsyncClient: | | async __aenter__(self: 'U') -> 'U' from httpx._client.AsyncClient | | async __aexit__(self, exc_type: 'type[BaseException] | None' = None, exc_value: 'BaseException | None' = None, traceback: 'TracebackType | None' = None) -> 'None' from httpx._client.AsyncClient | | async aclose(self) -> 'None' from httpx._client.AsyncClient | Close transport and proxies. | | async delete(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `DELETE` request. | | **Parameters**: See `httpx.request`. | | async get(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `GET` request. | | **Parameters**: See `httpx.request`. | | async head(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `HEAD` request. | | **Parameters**: See `httpx.request`. | | async options(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send an `OPTIONS` request. | | **Parameters**: See `httpx.request`. | | async patch(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `PATCH` request. | | **Parameters**: See `httpx.request`. | | async post(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `POST` request. | | **Parameters**: See `httpx.request`. | | async put(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Send a `PUT` request. | | **Parameters**: See `httpx.request`. | | async request(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.AsyncClient | Build and send a request. | | Equivalent to: | | ```python | request = client.build_request(...) | response = await client.send(request, ...) | ``` | | See `AsyncClient.build_request()`, `AsyncClient.send()` | and [Merging of configuration][0] for how the various parameters | are merged with client-level configuration. | | [0]: /advanced/#merging-of-configuration | | async send(self, request: 'Request', *, stream: 'bool' = False, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>) -> 'Response' from httpx._client.AsyncClient | Send a request. | | The request is sent as-is, unmodified. | | Typically you'll want to build one with `AsyncClient.build_request()` | so that any client-level configuration is merged into the request, | but passing an explicit `httpx.Request()` is supported as well. | | See also: [Request instances][0] | | [0]: /advanced/#request-instances | | stream(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'typing.AsyncIterator[Response]' from httpx._client.AsyncClient | Alternative to `httpx.request()` that streams the response body | instead of loading it into memory at once. | | **Parameters**: See `httpx.request`. | | See also: [Streaming Responses][0] | | [0]: /quickstart#streaming-responses | | ---------------------------------------------------------------------- | Methods inherited from httpx._client.BaseClient: | | build_request(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Request' | Build and return a request instance. | | * The `params`, `headers` and `cookies` arguments | are merged with any values set on the client. | * The `url` argument is merged with any `base_url` set on the client. | | See also: [Request instances][0] | | [0]: /advanced/#request-instances | | ---------------------------------------------------------------------- | Readonly properties inherited from httpx._client.BaseClient: | | is_closed | Check if the client being closed | | trust_env | | ---------------------------------------------------------------------- | Data descriptors inherited from httpx._client.BaseClient: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | auth | Authentication class used when none is passed at the request-level. | | See also [Authentication][0]. | | [0]: /quickstart/#authentication | | base_url | Base URL to use when sending requests with relative URLs. | | cookies | Cookie values to include when sending requests. | | event_hooks | | headers | HTTP headers to include when sending requests. | | params | Query parameters to include in the URL when sending requests. | | timeout
anthropic.DefaultHttpxClient
Python Library Documentation: class _DefaultHttpxClient in module anthropic class _DefaultHttpxClient(httpx.Client) | _DefaultHttpxClient(**kwargs: 'Any') -> 'None' | | Method resolution order: | _DefaultHttpxClient | httpx.Client | httpx._client.BaseClient | builtins.object | | Methods defined here: | | __init__(self, **kwargs: 'Any') -> 'None' from anthropic._base_client._DefaultHttpxClient | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from httpx.Client: | | __enter__(self: 'T') -> 'T' from httpx._client.Client | | __exit__(self, exc_type: 'type[BaseException] | None' = None, exc_value: 'BaseException | None' = None, traceback: 'TracebackType | None' = None) -> 'None' from httpx._client.Client | | close(self) -> 'None' from httpx._client.Client | Close transport and proxies. | | delete(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Send a `DELETE` request. | | **Parameters**: See `httpx.request`. | | get(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Send a `GET` request. | | **Parameters**: See `httpx.request`. | | head(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Send a `HEAD` request. | | **Parameters**: See `httpx.request`. | | options(self, url: 'URLTypes', *, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Send an `OPTIONS` request. | | **Parameters**: See `httpx.request`. | | patch(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Send a `PATCH` request. | | **Parameters**: See `httpx.request`. | | post(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Send a `POST` request. | | **Parameters**: See `httpx.request`. | | put(self, url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Send a `PUT` request. | | **Parameters**: See `httpx.request`. | | request(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Response' from httpx._client.Client | Build and send a request. | | Equivalent to: | | ```python | request = client.build_request(...) | response = client.send(request, ...) | ``` | | See `Client.build_request()`, `Client.send()` and | [Merging of configuration][0] for how the various parameters | are merged with client-level configuration. | | [0]: /advanced/#merging-of-configuration | | send(self, request: 'Request', *, stream: 'bool' = False, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>) -> 'Response' from httpx._client.Client | Send a request. | | The request is sent as-is, unmodified. | | Typically you'll want to build one with `Client.build_request()` | so that any client-level configuration is merged into the request, | but passing an explicit `httpx.Request()` is supported as well. | | See also: [Request instances][0] | | [0]: /advanced/#request-instances | | stream(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, auth: 'AuthTypes | UseClientDefault | None' = <httpx._client.UseClientDefault object at 0x000002A335283620>, follow_redirects: 'bool | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'typing.Iterator[Response]' from httpx._client.Client | Alternative to `httpx.request()` that streams the response body | instead of loading it into memory at once. | | **Parameters**: See `httpx.request`. | | See also: [Streaming Responses][0] | | [0]: /quickstart#streaming-responses | | ---------------------------------------------------------------------- | Methods inherited from httpx._client.BaseClient: | | build_request(self, method: 'str', url: 'URLTypes', *, content: 'RequestContent | None' = None, data: 'RequestData | None' = None, files: 'RequestFiles | None' = None, json: 'typing.Any | None' = None, params: 'QueryParamTypes | None' = None, headers: 'HeaderTypes | None' = None, cookies: 'CookieTypes | None' = None, timeout: 'TimeoutTypes | UseClientDefault' = <httpx._client.UseClientDefault object at 0x000002A335283620>, extensions: 'RequestExtensions | None' = None) -> 'Request' | Build and return a request instance. | | * The `params`, `headers` and `cookies` arguments | are merged with any values set on the client. | * The `url` argument is merged with any `base_url` set on the client. | | See also: [Request instances][0] | | [0]: /advanced/#request-instances | | ---------------------------------------------------------------------- | Readonly properties inherited from httpx._client.BaseClient: | | is_closed | Check if the client being closed | | trust_env | | ---------------------------------------------------------------------- | Data descriptors inherited from httpx._client.BaseClient: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | auth | Authentication class used when none is passed at the request-level. | | See also [Authentication][0]. | | [0]: /quickstart/#authentication | | base_url | Base URL to use when sending requests with relative URLs. | | cookies | Cookie values to include when sending requests. | | event_hooks | | headers | HTTP headers to include when sending requests. | | params | Query parameters to include in the URL when sending requests. | | timeout
anthropic.EnvToken
Python Library Documentation: class EnvToken in module anthropic.lib.credentials._providers class EnvToken(builtins.object) | EnvToken(env_var: 'str' = 'ANTHROPIC_AUTH_TOKEN') -> 'None' | | An :class:`AccessTokenProvider` that reads ``ANTHROPIC_AUTH_TOKEN`` at call time. | | Methods defined here: | | __call__(self, *, force_refresh: 'bool' = False) -> 'AccessToken' | Call self as a function. | | __init__(self, env_var: 'str' = 'ANTHROPIC_AUTH_TOKEN') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.HUMAN_PROMPT
Error rendering doc: No Python documentation found for '\n\nHuman:'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
anthropic.IdentityTokenFile
Python Library Documentation: class IdentityTokenFile in module anthropic.lib.credentials._providers class IdentityTokenFile(builtins.object) | IdentityTokenFile(path: "Union[str, 'os.PathLike[str]', None]" = None) -> 'None' | | An :class:`IdentityTokenProvider` that reads a JWT from a file on every call. | | Kubernetes projected service-account tokens (and similar) are rotated in place, | so the file MUST be re-read on every invocation rather than cached. | | Methods defined here: | | __call__(self) -> 'str' | Call self as a function. | | __init__(self, path: "Union[str, 'os.PathLike[str]', None]" = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Readonly properties defined here: | | path | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.IdentityTokenProvider
Python Library Documentation: _CallableGenericAlias in module typing
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
anthropic.InMemoryConfig
Python Library Documentation: class InMemoryConfig in module anthropic.lib.credentials._providers class InMemoryConfig(CredentialsFile) | InMemoryConfig(config: 'Dict[str, Any]', *, identity_token_provider: 'Optional[IdentityTokenProvider]' = None, http_client: 'Optional[httpx.Client]' = None) -> 'None' | | An :class:`AccessTokenProvider` driven by an in-memory config dict | (same shape as ``configs/<profile>.json``) rather than files on disk. | | Intended for callers that want to construct an :class:`anthropic.Anthropic` | client with a fully programmatic credentials setup — equivalent to the Go | SDK's ``option.WithConfig`` / TypeScript SDK's ``ClientOptions.config``. | | Both ``authentication.type`` discriminator values are supported: | | ``"oidc_federation"`` | ``authentication.credentials_path`` is **optional**. If set, exchanged | tokens are cached to / read from that file (same atomic 0600 write as | :class:`CredentialsFile`). If omitted, every call performs a fresh | jwt-bearer exchange with no on-disk cache. | | ``"user_oauth"`` | ``authentication.credentials_path`` is **required** — it is where the | access/refresh tokens live. Behaviour is identical to a file-backed | :class:`CredentialsFile` profile of the same shape. | | The implementation subclasses :class:`CredentialsFile` so the dispatch, | refresh-grant, disk-cache and atomic-write logic are shared verbatim; | only config loading and identity-token resolution are overridden. | | Method resolution order: | InMemoryConfig | CredentialsFile | builtins.object | | Methods defined here: | | __init__(self, config: 'Dict[str, Any]', *, identity_token_provider: 'Optional[IdentityTokenProvider]' = None, http_client: 'Optional[httpx.Client]' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | reload(self) -> 'None' | Drop the cached config so the next call re-reads it from disk. | | ``CredentialsFile`` caches the parsed config across calls to keep the | hot path cheap; a daemon that rotates a profile in place (e.g. flips | ``"type": "user_oauth"`` to ``"type": "oidc_federation"``) will not be | picked up automatically. Callers that need to react to such changes | can call ``reload()`` to force a fresh read on the next ``__call__``. | | ---------------------------------------------------------------------- | Methods inherited from CredentialsFile: | | __call__(self, *, force_refresh: 'bool' = False) -> 'AccessToken' | Call self as a function. | | bind_base_url(self, base_url: 'str') -> 'None' | Adopt the owning client's ``base_url`` as a fallback for the token | exchange. Slots between the config file's own ``base_url`` field and | the hard-coded default; a ``base_url`` in the config file still wins. | | The owning client binds exactly once at construction; sharing one | instance across clients with different ``base_url`` values is | unsupported and silently picks the last bind when the config file | doesn't pin a host. | | close(self) -> 'None' | Close the owned ``httpx.Client`` if we created one. | | extra_headers(self) -> 'Dict[str, str]' | Return headers derived from the config file (e.g. ``workspace_id``). | | Eagerly reads the config if not yet loaded. The returned dict is | suitable for merging into the client's default headers. | | ---------------------------------------------------------------------- | Readonly properties inherited from CredentialsFile: | | config_path | | profile | | resolved_base_url | The ``base_url`` declared in the profile config file, if any. | | Returns ``None`` when the config has no top-level ``base_url`` key — | callers should fall back to their own default rather than the | provider's bound/default value, so a profile that *doesn't* pin a | host never overrides an explicit client setting. Loads the config | on first access. | | ---------------------------------------------------------------------- | Data descriptors inherited from CredentialsFile: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.InputJsonEvent
Python Library Documentation: class InputJsonEvent in module anthropic.lib.streaming._types
class InputJsonEvent(anthropic.BaseModel)
| InputJsonEvent(**extra_data: Any) -> None
|
| Method resolution order:
| InputJsonEvent
| anthropic.BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'partial_json': <class 'str'>, 'snapshot': <class '...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.lib.streaming._ty...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'partial_json': FieldInfo(annotation=str, requi...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="InputJsonEvent", valid...
|
| __signature__ = <Signature (*, type: Literal['input_json'], part...tr,...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.BaseModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'partial_json': FieldInfo(annotation=str, required=Tru...
anthropic.InternalServerError
Python Library Documentation: class InternalServerError in module anthropic
class InternalServerError(APIStatusError)
| InternalServerError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| InternalServerError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.MessageStopEvent
Python Library Documentation: class MessageStopEvent in module anthropic.lib.streaming._types
class MessageStopEvent(anthropic.types.raw_message_stop_event.RawMessageStopEvent)
| MessageStopEvent(**extra_data: Any) -> None
|
| Method resolution order:
| MessageStopEvent
| anthropic.types.raw_message_stop_event.RawMessageStopEvent
| anthropic.BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'message': <class 'anthropic.types.message.Message'...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'message': FieldInfo(annotation=Message, requir...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="MessageStopEvent", val...
|
| __signature__ = <Signature (*, type: Literal['message_stop'], me...ype...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.BaseModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'message': FieldInfo(annotation=Message, required=True...
anthropic.MessageStream
Python Library Documentation: class MessageStream in module anthropic.lib.streaming._messages
class MessageStream(typing.Generic)
| MessageStream(raw_stream: 'Stream[RawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
|
| Method resolution order:
| MessageStream
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'Self'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| __init__(self, raw_stream: 'Stream[RawMessageStreamEvent]', output_format: 'ResponseFormatT | NotGiven') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> 'Iterator[ParsedMessageStreamEvent[ResponseFormatT]]'
|
| __next__(self) -> 'ParsedMessageStreamEvent[ResponseFormatT]'
|
| __stream__(self) -> 'Iterator[ParsedMessageStreamEvent[ResponseFormatT]]'
|
| __stream_text__(self) -> 'Iterator[str]'
|
| close(self) -> 'None'
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| get_final_message(self) -> 'ParsedMessage[ResponseFormatT]'
| Waits until the stream has been read to completion and returns
| the accumulated `Message` object.
|
| get_final_text(self) -> 'str'
| Returns all `text` content blocks concatenated together.
|
| > [!NOTE]
| > Currently the API will only respond with a single content block.
|
| Will raise an error if no `text` content blocks were returned.
|
| until_done(self) -> 'None'
| Blocks until the stream has been consumed
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| current_message_snapshot
|
| request_id
|
| response
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'text_stream': 'Iterator[str]'}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.MessageStreamEvent
Python Library Documentation: _AnnotatedAlias in module typing Annotated = typing.Union[anthropic.lib.streaming._types.Text...ropic.lib.streaming._types.ContentBlockStopEvent]
anthropic.MessageStreamManager
Python Library Documentation: class MessageStreamManager in module anthropic.lib.streaming._messages
class MessageStreamManager(typing.Generic)
| MessageStreamManager(api_request: 'Callable[[], Stream[RawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven') -> 'None'
|
| Wrapper over MessageStream that is returned by `.stream()`.
|
| ```py
| with client.messages.stream(...) as stream:
| for chunk in stream:
| ...
| ```
|
| Method resolution order:
| MessageStreamManager
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'MessageStream[ResponseFormatT]'
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None'
|
| __init__(self, api_request: 'Callable[[], Stream[RawMessageStreamEvent]]', *, output_format: 'ResponseFormatT | NotGiven') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~ResponseFormatT],)
|
| __parameters__ = (~ResponseFormatT,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.Middleware
Python Library Documentation: class Middleware in module anthropic class Middleware(builtins.object) | Base class for client-level middleware. | | Subclass and override `handle` (used by the sync client) and/or `handle_async` | (used by the async client). The default implementations delegate straight to | the rest of the chain. | | Methods defined here: | | handle(self, request: 'APIRequest', call_next: 'CallNext') -> 'APIResponse[Any]' from anthropic._middleware.Middleware | | async handle_async(self, request: 'APIRequest', call_next: 'AsyncCallNext') -> 'AsyncAPIResponse[Any]' from anthropic._middleware.Middleware | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.MiddlewareCallable
Python Library Documentation: _CallableGenericAlias in module anthropic
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
anthropic.MiddlewareInput
Python Library Documentation: _UnionGenericAlias in module anthropic
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
anthropic.NOT_GIVEN
Python Library Documentation: NotGiven in module anthropic object class NotGiven(builtins.object) | For parameters with a meaningful None value, we need to distinguish between | the user explicitly passing None, and the user not passing the parameter at | all. | | User code shouldn't need to use not_given directly. | | For example: | | ```py | def create(timeout: Timeout | None | NotGiven = not_given): ... | | | create(timeout=1) # 1s timeout | create(timeout=None) # No timeout | create() # Default timeout behavior | ``` | | Methods defined here: | | __bool__(self) -> 'Literal[False]' from anthropic._types.NotGiven | | __repr__(self) -> 'str' from anthropic._types.NotGiven | Return repr(self). | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.NoneType
Python Library Documentation: class NoneType in module builtins class NoneType(object) | Methods defined here: | | __bool__(self, /) | True if self else False | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.
anthropic.NotFoundError
Python Library Documentation: class NotFoundError in module anthropic
class NotFoundError(APIStatusError)
| NotFoundError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| NotFoundError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[404]'}
|
| status_code = 404
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.NotGiven
Python Library Documentation: class NotGiven in module anthropic class NotGiven(builtins.object) | For parameters with a meaningful None value, we need to distinguish between | the user explicitly passing None, and the user not passing the parameter at | all. | | User code shouldn't need to use not_given directly. | | For example: | | ```py | def create(timeout: Timeout | None | NotGiven = not_given): ... | | | create(timeout=1) # 1s timeout | create(timeout=None) # No timeout | create() # Default timeout behavior | ``` | | Methods defined here: | | __bool__(self) -> 'Literal[False]' from anthropic._types.NotGiven | | __repr__(self) -> 'str' from anthropic._types.NotGiven | Return repr(self). | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.Omit
Python Library Documentation: class Omit in module anthropic
class Omit(builtins.object)
| To explicitly omit something from being sent in a request, use `omit`.
|
| ```py
| # as the default `Content-Type` header is `application/json` that will be sent
| client.post("/upload/files", files={"file": b"my raw file content"})
|
| # you can't explicitly override the header as it has to be dynamically generated
| # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
| client.post(..., headers={"Content-Type": "multipart/form-data"})
|
| # instead you can remove the default `application/json` header by passing omit
| client.post(..., headers={"Content-Type": omit})
| ```
|
| Methods defined here:
|
| __bool__(self) -> 'Literal[False]' from anthropic._types.Omit
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
anthropic.OverloadedError
Python Library Documentation: class OverloadedError in module anthropic
class OverloadedError(APIStatusError)
| OverloadedError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| OverloadedError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[529]'}
|
| status_code = 529
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.ParsedBetaContentBlockStopEvent
Python Library Documentation: class ParsedBetaContentBlockStopEvent in module anthropic.lib.streaming._beta_types
class ParsedBetaContentBlockStopEvent(anthropic.types.beta.beta_raw_content_block_stop_event.BetaRawContentBlockStopEvent, anthropic._models.GenericModel, typing.Generic)
| ParsedBetaContentBlockStopEvent(*, index: int, type: Literal['content_block_stop'], content_block: Annotated[Union[anthropic.types.beta.parsed_beta_message.ParsedBetaTextBlock, anthropic.types.beta.beta_thinking_block.BetaThinkingBlock, anthropic.types.beta.beta_redacted_thinking_block.BetaRedactedThinkingBlock, anthropic.types.beta.beta_tool_use_block.BetaToolUseBlock, anthropic.types.beta.beta_server_tool_use_block.BetaServerToolUseBlock, anthropic.types.beta.beta_web_search_tool_result_block.BetaWebSearchToolResultBlock, anthropic.types.beta.beta_web_fetch_tool_result_block.BetaWebFetchToolResultBlock, anthropic.types.beta.beta_advisor_tool_result_block.BetaAdvisorToolResultBlock, anthropic.types.beta.beta_code_execution_tool_result_block.BetaCodeExecutionToolResultBlock, anthropic.types.beta.beta_bash_code_execution_tool_result_block.BetaBashCodeExecutionToolResultBlock, anthropic.types.beta.beta_text_editor_code_execution_tool_result_block.BetaTextEditorCodeExecutionToolResultBlock, anthropic.types.beta.beta_tool_search_tool_result_block.BetaToolSearchToolResultBlock, anthropic.types.beta.beta_mcp_tool_use_block.BetaMCPToolUseBlock, anthropic.types.beta.beta_mcp_tool_result_block.BetaMCPToolResultBlock, anthropic.types.beta.beta_container_upload_block.BetaContainerUploadBlock, anthropic.types.beta.beta_compaction_block.BetaCompactionBlock, anthropic.types.beta.beta_fallback_block.BetaFallbackBlock], PropertyInfo(alias='None', format=None, format_template='None', discriminator='type')], **extra_data: Any) -> None
|
| Method resolution order:
| ParsedBetaContentBlockStopEvent
| anthropic.types.beta.beta_raw_content_block_stop_event.BetaRawContentBlockStopEvent
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'content_block': typing.Annotated[typing.Union[anth...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic.types.beta.beta_raw_content_block_...
|
| __parameters__ = (~ResponseFormatT,)
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'content_block': FieldInfo(annotation=Union[Par...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedBetaContentBlock...
|
| __signature__ = <Signature (*, index: int, type: Literal['conten...scr...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'content_block': FieldInfo(annotation=Union[ParsedBeta...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.ParsedBetaMessageStopEvent
Python Library Documentation: class ParsedBetaMessageStopEvent in module anthropic.lib.streaming._beta_types
class ParsedBetaMessageStopEvent(anthropic.types.beta.beta_raw_message_stop_event.BetaRawMessageStopEvent, anthropic._models.GenericModel, typing.Generic)
| ParsedBetaMessageStopEvent(*, type: Literal['message_stop'], message: anthropic.types.beta.parsed_beta_message.ParsedBetaMessage[TypeVar], **extra_data: Any) -> None
|
| Method resolution order:
| ParsedBetaMessageStopEvent
| anthropic.types.beta.beta_raw_message_stop_event.BetaRawMessageStopEvent
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'message': <class 'anthropic.types.beta.parsed_beta...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic.types.beta.beta_raw_message_stop_e...
|
| __parameters__ = (~ResponseFormatT,)
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'message': FieldInfo(annotation=ParsedBetaMessa...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedBetaMessageStopE...
|
| __signature__ = <Signature (*, type: Literal['message_stop'], me...Bet...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'message': FieldInfo(annotation=ParsedBetaMessage[Type...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.ParsedBetaMessageStreamEvent
Python Library Documentation: _AnnotatedAlias in module typing Annotated = typing.Union[anthropic.lib.streaming._beta_types...ming._beta_types.ParsedBetaContentBlockStopEvent]
anthropic.ParsedBetaTextEvent
Python Library Documentation: class ParsedBetaTextEvent in module anthropic.lib.streaming._beta_types
class ParsedBetaTextEvent(anthropic.BaseModel)
| ParsedBetaTextEvent(*, type: Literal['text'], text: str, snapshot: str, **extra_data: Any) -> None
|
| Method resolution order:
| ParsedBetaTextEvent
| anthropic.BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Methods defined here:
|
| parsed_snapshot(self) -> Dict[str, Any]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'snapshot': <class 'str'>, 'text': <class 'str'>, '...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.lib.streaming._be...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'snapshot': FieldInfo(annotation=str, required=...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedBetaTextEvent", ...
|
| __signature__ = <Signature (*, type: Literal['text'], text: str, snaps...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.BaseModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'snapshot': FieldInfo(annotation=str, required=True), ...
anthropic.ParsedContentBlockStopEvent
Python Library Documentation: class ParsedContentBlockStopEvent in module anthropic.lib.streaming._types
class ParsedContentBlockStopEvent(anthropic.types.raw_content_block_stop_event.RawContentBlockStopEvent, anthropic._models.GenericModel, typing.Generic)
| ParsedContentBlockStopEvent() -> None
|
| Method resolution order:
| ParsedContentBlockStopEvent
| anthropic.types.raw_content_block_stop_event.RawContentBlockStopEvent
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'content_block': typing.Annotated[typing.Union[anth...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic.types.raw_content_block_stop_event...
|
| __parameters__ = (~ResponseFormatT,)
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'content_block': FieldInfo(annotation=Union[Par...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedContentBlockStop...
|
| __signature__ = <Signature (*, index: int, type: Literal['conten...scr...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'content_block': FieldInfo(annotation=Union[ParsedText...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.ParsedMessageStopEvent
Python Library Documentation: class ParsedMessageStopEvent in module anthropic.lib.streaming._types
class ParsedMessageStopEvent(anthropic.types.raw_message_stop_event.RawMessageStopEvent, anthropic._models.GenericModel, typing.Generic)
| ParsedMessageStopEvent() -> None
|
| Method resolution order:
| ParsedMessageStopEvent
| anthropic.types.raw_message_stop_event.RawMessageStopEvent
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'message': <class 'anthropic.types.parsed_message.P...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic.types.raw_message_stop_event.RawMe...
|
| __parameters__ = (~ResponseFormatT,)
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'definitions': [{'cls': <class 'anthropic....
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'message': FieldInfo(annotation=ParsedMessage[T...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ParsedMessageStopEvent...
|
| __signature__ = <Signature (*, type: Literal['message_stop'], me...rse...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'message': FieldInfo(annotation=ParsedMessage[TypeVar]...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.ParsedMessageStreamEvent
Python Library Documentation: _AnnotatedAlias in module typing Annotated = typing.Union[anthropic.lib.streaming._types.Text...lib.streaming._types.ParsedContentBlockStopEvent]
anthropic.PermissionDeniedError
Python Library Documentation: class PermissionDeniedError in module anthropic
class PermissionDeniedError(APIStatusError)
| PermissionDeniedError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| PermissionDeniedError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[403]'}
|
| status_code = 403
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.ProxiesTypes
Python Library Documentation: _UnionGenericAlias in module anthropic
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
anthropic.RateLimitError
Python Library Documentation: class RateLimitError in module anthropic
class RateLimitError(APIStatusError)
| RateLimitError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| RateLimitError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[429]'}
|
| status_code = 429
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.RequestOptions
Python Library Documentation: class RequestOptions in module anthropic
class RequestOptions(builtins.dict)
| Method resolution order:
| RequestOptions
| builtins.dict
| builtins.object
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'extra_json': ForwardRef('AnyMapping', module='anth...
|
| __closed__ = None
|
| __extra_items__ = typing_extensions.NoExtraItems
|
| __mutable_keys__ = frozenset({'extra_json', 'follow_redirects', 'heade...
|
| __optional_keys__ = frozenset({'extra_json', 'follow_redirects', 'head...
|
| __orig_bases__ = (typing_extensions.TypedDict,)
|
| __readonly_keys__ = frozenset()
|
| __required_keys__ = frozenset()
|
| __total__ = False
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from builtins.dict:
|
| __hash__ = None
anthropic.RequestTooLargeError
Python Library Documentation: class RequestTooLargeError in module anthropic
class RequestTooLargeError(APIStatusError)
| RequestTooLargeError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| RequestTooLargeError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[413]'}
|
| status_code = 413
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.RetryableError
Python Library Documentation: class RetryableError in module anthropic
class RetryableError(AnthropicError)
| An error that opts into the SDK's retry policy: raise it (e.g. from
| middleware) to have the request attempt retried.
|
| The request is only retried while `max_retries` has not been exhausted;
| once exhausted the error propagates to the caller as-is.
|
| Method resolution order:
| RetryableError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.Exception:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.StaticToken
Python Library Documentation: class StaticToken in module anthropic.lib.credentials._providers class StaticToken(builtins.object) | StaticToken(token: 'str') -> 'None' | | An :class:`AccessTokenProvider` that always returns a fixed token with no expiry. | | Methods defined here: | | __call__(self, *, force_refresh: 'bool' = False) -> 'AccessToken' | Call self as a function. | | __init__(self, token: 'str') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.Stream
Python Library Documentation: class Stream in module anthropic
class Stream(typing.Generic)
| Stream(*, cast_to: 'type[_T]', response: 'httpx.Response', client: 'Anthropic', options: 'Optional[FinalRequestOptions]' = None) -> 'None'
|
| Provides the core interface to iterate over a synchronous stream response.
|
| Method resolution order:
| Stream
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'Self' from anthropic._streaming.Stream
|
| __exit__(self, exc_type: 'type[BaseException] | None', exc: 'BaseException | None', exc_tb: 'TracebackType | None') -> 'None' from anthropic._streaming.Stream
|
| __init__(self, *, cast_to: 'type[_T]', response: 'httpx.Response', client: 'Anthropic', options: 'Optional[FinalRequestOptions]' = None) -> 'None' from anthropic._streaming.Stream
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> 'Iterator[_T]' from anthropic._streaming.Stream
|
| __next__(self) -> '_T' from anthropic._streaming.Stream
|
| __stream__(self) -> 'Iterator[_T]' from anthropic._streaming.Stream
|
| close(self) -> 'None' from anthropic._streaming.Stream
| Close the response and release the connection.
|
| Automatically called if the response body is read to completion.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| raw_events(response: 'httpx.Response') -> 'Iterator[ServerSentEvent]' from anthropic._streaming.Stream
| Iterate the raw Server-Sent Events from `response`, before any JSON
| parsing or event-name filtering.
|
| This reads the response body directly, so the response is consumed.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'_decoder': 'SSEBytesDecoder', '_options': 'Optiona...
|
| __orig_bases__ = (typing.Generic[~_T],)
|
| __parameters__ = (~_T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
anthropic.TextEvent
Python Library Documentation: class TextEvent in module anthropic.lib.streaming._types
class TextEvent(anthropic.BaseModel)
| TextEvent(**extra_data: Any) -> None
|
| Method resolution order:
| TextEvent
| anthropic.BaseModel
| pydantic.main.BaseModel
| builtins.object
|
| Methods defined here:
|
| parsed_snapshot(self) -> Dict[str, Any]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'snapshot': <class 'str'>, 'text': <class 'str'>, '...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.lib.streaming._ty...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'snapshot': FieldInfo(annotation=str, required=...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="TextEvent", validator=...
|
| __signature__ = <Signature (*, type: Literal['text'], text: str, snaps...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.BaseModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'snapshot': FieldInfo(annotation=str, required=True), ...
anthropic.Timeout
Python Library Documentation: class Timeout in module anthropic class Timeout(builtins.object) | Timeout(timeout: 'TimeoutTypes | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, *, connect: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, read: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, write: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, pool: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>) -> 'None' | | Timeout configuration. | | **Usage**: | | Timeout(None) # No timeouts. | Timeout(5.0) # 5s timeout on all operations. | Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. | Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. | Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. | # 5s timeout elsewhere. | | Methods defined here: | | __eq__(self, other: 'typing.Any') -> 'bool' from httpx._config.Timeout | Return self==value. | | __init__(self, timeout: 'TimeoutTypes | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, *, connect: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, read: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, write: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>, pool: 'None | float | UnsetType' = <httpx._config.UnsetType object at 0x000002A336D34A40>) -> 'None' from httpx._config.Timeout | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) -> 'str' from httpx._config.Timeout | Return repr(self). | | as_dict(self) -> 'dict[str, float | None]' from httpx._config.Timeout | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
anthropic.TokenCache
Python Library Documentation: class TokenCache in module anthropic.lib.credentials._cache class TokenCache(builtins.object) | TokenCache(provider: 'AccessTokenProvider', *, advisory_refresh_seconds: 'int' = 120, mandatory_refresh_seconds: 'int' = 30, time_source: 'Callable[[], float]' = <built-in function time>) -> 'None' | | Thread-safe cache wrapping an :class:`AccessTokenProvider` with two-tier | proactive refresh and single-flight semantics. | | Refresh policy on each :meth:`get_token` call: | | * No cached token → call provider (blocking), cache, return. | * Cached with ``expires_at=None`` → return cached forever (never refresh). | * More than ``advisory_refresh_seconds`` remaining → return cached. | * Between ``mandatory_refresh_seconds`` and ``advisory_refresh_seconds`` | remaining (advisory window) → try provider; on success swap cache; on | failure log a warning and return the stale cached token. If another | caller is already refreshing, the advisory caller just returns the | cached token — no second refresh, no waiting. | * Less than ``mandatory_refresh_seconds`` remaining or already expired | (mandatory window) → call provider; on failure RAISE. Concurrent | mandatory callers wait on a shared ``Event`` so exactly one provider | call is in flight. | | The lock is released before the provider call so a 30-second HTTP POST | doesn't serialize unrelated callers through a single thread. This matters | under async: ``asyncify(get_token)`` runs on the thread pool, and holding | the lock across the network call would pin an async worker for the whole | exchange. | | Methods defined here: | | __init__(self, provider: 'AccessTokenProvider', *, advisory_refresh_seconds: 'int' = 120, mandatory_refresh_seconds: 'int' = 30, time_source: 'Callable[[], float]' = <built-in function time>) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | get_token(self) -> 'str' | Return a valid bearer token, refreshing if necessary. | | invalidate(self) -> 'None' | Clear the cached token so the next :meth:`get_token` re-invokes the provider. | | Also sets a one-shot ``force_refresh`` flag so on-disk providers skip | their freshness short-circuit instead of re-serving the revoked token. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.Transport
Python Library Documentation: class BaseTransport in module anthropic class BaseTransport(builtins.object) | Methods defined here: | | __enter__(self: 'T') -> 'T' from httpx._transports.base.BaseTransport | | __exit__(self, exc_type: 'type[BaseException] | None' = None, exc_value: 'BaseException | None' = None, traceback: 'TracebackType | None' = None) -> 'None' from httpx._transports.base.BaseTransport | | close(self) -> 'None' from httpx._transports.base.BaseTransport | | handle_request(self, request: 'Request') -> 'Response' from httpx._transports.base.BaseTransport | Send a single HTTP request and return a response. | | Developers shouldn't typically ever need to call into this API directly, | since the Client class provides all the higher level user-facing API | niceties. | | In order to properly release any network resources, the response | stream should *either* be consumed immediately, with a call to | `response.stream.read()`, or else the `handle_request` call should | be followed with a try/finally block to ensuring the stream is | always closed. | | Example usage: | | with httpx.HTTPTransport() as transport: | req = httpx.Request( | method=b"GET", | url=(b"https", b"www.example.com", 443, b"/"), | headers=[(b"Host", b"www.example.com")], | ) | resp = transport.handle_request(req) | body = resp.stream.read() | print(resp.status_code, resp.headers, body) | | | Takes a `Request` instance as the only argument. | | Returns a `Response` instance. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.TypeAlias
Python Library Documentation: _SpecialForm in module typing
TypeAlias = typing.TypeAlias
Special form for marking type aliases.
Use TypeAlias to indicate that an assignment should
be recognized as a proper type alias definition by type
checkers.
For example::
Predicate: TypeAlias = Callable[..., bool]
It's invalid when used anywhere except as in the example above.
anthropic.UnprocessableEntityError
Python Library Documentation: class UnprocessableEntityError in module anthropic
class UnprocessableEntityError(APIStatusError)
| UnprocessableEntityError(message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None'
|
| Method resolution order:
| UnprocessableEntityError
| APIStatusError
| APIError
| AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'status_code': 'Literal[422]'}
|
| status_code = 422
|
| ----------------------------------------------------------------------
| Methods inherited from APIStatusError:
|
| __init__(self, message: 'str', *, response: 'httpx.Response', body: 'object | None') -> 'None' from anthropic._exceptions.APIStatusError
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.WorkloadIdentityCredentials
Python Library Documentation: class WorkloadIdentityCredentials in module anthropic.lib.credentials._workload class WorkloadIdentityCredentials(builtins.object) | WorkloadIdentityCredentials(*, identity_token_provider: 'IdentityTokenProvider', federation_rule_id: 'str', organization_id: 'str', service_account_id: 'Optional[str]' = None, workspace_id: 'Optional[str]' = None, scope: 'Optional[str]' = None, http_client: 'Optional[httpx.Client]' = None) -> 'None' | | Exchanges an external OIDC JWT for an Anthropic access token via the | RFC 7523 ``jwt-bearer`` grant. | | This is an :class:`AccessTokenProvider`: calling it performs a *fresh* token | exchange. Wrap in a :class:`TokenCache` (done automatically when passed as | ``credentials=`` to :class:`anthropic.Anthropic`) to avoid exchanging on every | request. | | Args: | organization_id: The organization's raw UUID string (organizations do | not use tagged IDs). | workspace_id: Optional ``wrkspc_*`` tagged ID, or the literal | ``"default"`` to scope the token to the organization's default | workspace. When omitted the server picks the rule's sole enabled | workspace, else the org default if the rule covers it. Required | when the rule enables more than one non-default workspace, or to | target a specific workspace other than the one the server would | pick. The minted token is workspace-scoped: per-request workspace | selection (the ``anthropic-workspace-id`` header) is not supported | for federation tokens — switching workspaces requires a new token | exchange with a different ``workspace_id``. | | Methods defined here: | | __call__(self, *, force_refresh: 'bool' = False) -> 'AccessToken' | Call self as a function. | | __enter__(self) -> "'WorkloadIdentityCredentials'" | | __exit__(self, exc_type: 'Optional[Type[BaseException]]', exc: 'Optional[BaseException]', tb: 'Optional[TracebackType]') -> 'None' | | __init__(self, *, identity_token_provider: 'IdentityTokenProvider', federation_rule_id: 'str', organization_id: 'str', service_account_id: 'Optional[str]' = None, workspace_id: 'Optional[str]' = None, scope: 'Optional[str]' = None, http_client: 'Optional[httpx.Client]' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | bind_base_url(self, base_url: 'str') -> 'None' | Set the API ``base_url`` the token exchange POSTs to. | | Called by :class:`anthropic.Anthropic` when this object is passed as | ``credentials=``, so callers don't pass the same URL twice. For | standalone use (no client) or tests, call this directly. | | close(self) -> 'None' | Close the underlying ``httpx.Client`` if we created it. | | ---------------------------------------------------------------------- | Readonly properties defined here: | | scope | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.WorkloadIdentityError
Python Library Documentation: class WorkloadIdentityError in module anthropic.lib.credentials._workload
class WorkloadIdentityError(anthropic.AnthropicError)
| WorkloadIdentityError(message: 'str', *, status_code: 'Optional[int]' = None, body: 'Any' = None, request_id: 'Optional[str]' = None) -> 'None'
|
| Raised when the OIDC token exchange (``POST /v1/oauth/token``) fails.
|
| Method resolution order:
| WorkloadIdentityError
| anthropic.AnthropicError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str', *, status_code: 'Optional[int]' = None, body: 'Any' = None, request_id: 'Optional[str]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'body': 'Any', 'request_id': 'Optional[str]', 'stat...
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic.AnthropicError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
anthropic.beta_async_tool
Python Library Documentation: function beta_async_tool in module anthropic
beta_async_tool(func: 'AsyncFunctionT | None' = None, *, name: 'str | None' = None, description: 'str | None' = None, input_schema: 'InputSchema | type[BaseModel] | None' = None, defer_loading: 'bool | None' = None, cache_control: 'BetaCacheControlEphemeralParam | None' = None, allowed_callers: "list[Literal['direct', 'code_execution_20250825', 'code_execution_20260120', 'code_execution_20260521']] | None" = None, eager_input_streaming: 'bool | None' = None, input_examples: 'Iterable[dict[str, object]] | None' = None, strict: 'bool | None' = None) -> 'BetaAsyncFunctionTool[AsyncFunctionT] | Callable[[AsyncFunctionT], BetaAsyncFunctionTool[AsyncFunctionT]]'
Create an AsyncFunctionTool from a function with automatic schema inference.
Can be used as a decorator with or without parentheses:
@async_tool
async def my_func(x: int) -> str: ...
@async_tool()
async def my_func(x: int) -> str: ...
@async_tool(name="custom_name")
async def my_func(x: int) -> str: ...
anthropic.beta_tool
Python Library Documentation: function beta_tool in module anthropic
beta_tool(func: 'FunctionT | None' = None, *, name: 'str | None' = None, description: 'str | None' = None, input_schema: 'InputSchema | type[BaseModel] | None' = None, defer_loading: 'bool | None' = None, cache_control: 'BetaCacheControlEphemeralParam | None' = None, allowed_callers: "list[Literal['direct', 'code_execution_20250825', 'code_execution_20260120', 'code_execution_20260521']] | None" = None, eager_input_streaming: 'bool | None' = None, input_examples: 'Iterable[dict[str, object]] | None' = None, strict: 'bool | None' = None) -> 'BetaFunctionTool[FunctionT] | Callable[[FunctionT], BetaFunctionTool[FunctionT]]'
Create a FunctionTool from a function with automatic schema inference.
Can be used as a decorator with or without parentheses:
@function_tool
def my_func(x: int) -> str: ...
@function_tool()
def my_func(x: int) -> str: ...
@function_tool(name="custom_name")
def my_func(x: int) -> str: ...
anthropic.default_credentials
Python Library Documentation: function default_credentials in module anthropic.lib.credentials._chain
default_credentials(*, base_url: 'str' = 'https://api.anthropic.com') -> 'Optional[CredentialResult]'
Resolve a :class:`CredentialResult` from the environment per the
credential-resolution spec. First match wins.
Implements steps 2-5 of the spec precedence chain (step 1 is handled at
the client constructor level, above this function):
Step 2a: ``ANTHROPIC_API_KEY`` → return ``None`` so the client uses its
existing ``X-Api-Key`` header path. (API keys are not Bearer
tokens, so they can't flow through this chain.)
Step 2b: ``ANTHROPIC_AUTH_TOKEN`` → :class:`StaticToken` (Bearer).
Step 3: ``ANTHROPIC_PROFILE`` / ``ANTHROPIC_CONFIG_DIR`` set, or the
``active_config`` pointer file exists → load that profile.
This is *explicit profile selection*; failures propagate.
Step 4: ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID``
+ ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` → direct jwt-bearer
exchange via :class:`WorkloadIdentityCredentials`. Critically,
step 4 sits **between** explicit profile (step 3) and
fallback profile (step 5): a machine with WIF env vars wired
up must use WIF even if a leftover ``default`` profile exists
on disk, but a user who explicitly ``ANTHROPIC_PROFILE=dev``
still gets their profile.
Step 5: Fallback active profile from disk (``configs/default.json``
or whatever ``active_config`` points at). Errors at this step
are swallowed and the chain falls through — a corrupt
unselected profile shouldn't break an otherwise-explicit
api_key= path.
Returns ``None`` when nothing matches — the client will fall back to
its normal "no auth configured" error.
anthropic.exchange_federation_assertion
Python Library Documentation: function exchange_federation_assertion in module anthropic.lib.credentials._workload
exchange_federation_assertion(*, assertion: 'Union[str, SecretStr]', federation_rule_id: 'str', organization_id: 'str', service_account_id: 'Optional[str]' = None, workspace_id: 'Optional[str]' = None, base_url: 'Optional[str]' = None, http_client: 'Optional[httpx.Client]' = None) -> 'AccessToken'
Perform a single RFC 7523 ``jwt-bearer`` exchange and return the resulting
:class:`AccessToken`.
This is a one-shot convenience wrapper around :class:`WorkloadIdentityCredentials`
for callers that already have the assertion JWT in hand and just want the
Anthropic access token back (no caching, no provider plumbing).
``assertion`` may be a :class:`pydantic.SecretStr` to keep it redacted
end-to-end; a plain ``str`` is wrapped on entry.
anthropic.file_from_path
Python Library Documentation: function file_from_path in module anthropic file_from_path(path: 'str') -> 'FileTypes'
anthropic.lib
Python Library Documentation: package anthropic.lib in anthropic
NAME
anthropic.lib
PACKAGE CONTENTS
_extras (package)
_files
_retry
_scoped_client
_stainless_helpers
aws (package)
bedrock (package)
credentials (package)
environments (package)
foundry
google_cloud (package)
middleware (package)
sessions (package)
streaming (package)
tools (package)
vertex (package)
SUBMODULES
_parse
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\anthropic\lib\__init__.py
anthropic.not_given
Python Library Documentation: NotGiven in module anthropic object class NotGiven(builtins.object) | For parameters with a meaningful None value, we need to distinguish between | the user explicitly passing None, and the user not passing the parameter at | all. | | User code shouldn't need to use not_given directly. | | For example: | | ```py | def create(timeout: Timeout | None | NotGiven = not_given): ... | | | create(timeout=1) # 1s timeout | create(timeout=None) # No timeout | create() # Default timeout behavior | ``` | | Methods defined here: | | __bool__(self) -> 'Literal[False]' from anthropic._types.NotGiven | | __repr__(self) -> 'str' from anthropic._types.NotGiven | Return repr(self). | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
anthropic.omit
Python Library Documentation: Omit in module anthropic object
class Omit(builtins.object)
| To explicitly omit something from being sent in a request, use `omit`.
|
| ```py
| # as the default `Content-Type` header is `application/json` that will be sent
| client.post("/upload/files", files={"file": b"my raw file content"})
|
| # you can't explicitly override the header as it has to be dynamically generated
| # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
| client.post(..., headers={"Content-Type": "multipart/form-data"})
|
| # instead you can remove the default `application/json` header by passing omit
| client.post(..., headers={"Content-Type": omit})
| ```
|
| Methods defined here:
|
| __bool__(self) -> 'Literal[False]' from anthropic._types.Omit
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
anthropic.pagination
Python Library Documentation: module anthropic.pagination in anthropic
NAME
anthropic.pagination - # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
CLASSES
anthropic._base_client.BaseAsyncPage[TypeVar](anthropic._base_client.BaseAsyncPage)
AsyncBidirectionalPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncTokenPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
anthropic._base_client.BasePage[TypeVar](anthropic._base_client.BasePage)
AsyncBidirectionalPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncTokenPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncBidirectionalPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncTokenPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
anthropic._base_client.BaseSyncPage[TypeVar](anthropic._base_client.BaseSyncPage)
SyncBidirectionalPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncTokenPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
typing.Generic(builtins.object)
AsyncBidirectionalPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
AsyncTokenPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncBidirectionalPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
SyncTokenPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
class AsyncBidirectionalPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| AsyncBidirectionalPageCursor(**extra_data: Any) -> None
|
| Method resolution order:
| AsyncBidirectionalPageCursor
| anthropic._base_client.BaseAsyncPage[TypeVar]
| anthropic._base_client.BaseAsyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'next_page': typing.Optio...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseAsyncPage[TypeVar...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.AsyncB...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="AsyncBidirectionalPage...
|
| __signature__ = <Signature (*, data: List[~_T], next_page: Optio...Opt...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseAsyncPage:
|
| async __aiter__(self) -> 'AsyncIterator[_T]'
|
| async get_next_page(self: 'AsyncPageT') -> 'AsyncPageT'
|
| async iter_pages(self: 'AsyncPageT') -> 'AsyncIterator[AsyncPageT]'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BasePage:
|
| has_next_page(self) -> 'bool'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
class AsyncPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| AsyncPage(**extra_data: Any) -> None
|
| Method resolution order:
| AsyncPage
| anthropic._base_client.BaseAsyncPage[TypeVar]
| anthropic._base_client.BaseAsyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| has_next_page(self) -> bool
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'first_id': typing.Option...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseAsyncPage[TypeVar...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.AsyncP...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="AsyncPage", validator=...
|
| __signature__ = <Signature (*, data: List[~_T], has_more: Option...Opt...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseAsyncPage:
|
| async __aiter__(self) -> 'AsyncIterator[_T]'
|
| async get_next_page(self: 'AsyncPageT') -> 'AsyncPageT'
|
| async iter_pages(self: 'AsyncPageT') -> 'AsyncIterator[AsyncPageT]'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
class AsyncPageCursor(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| AsyncPageCursor(**extra_data: Any) -> None
|
| Method resolution order:
| AsyncPageCursor
| anthropic._base_client.BaseAsyncPage[TypeVar]
| anthropic._base_client.BaseAsyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'next_page': typing.Optio...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseAsyncPage[TypeVar...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.AsyncP...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="AsyncPageCursor", vali...
|
| __signature__ = <Signature (*, data: List[~_T], next_page: Optional[st...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseAsyncPage:
|
| async __aiter__(self) -> 'AsyncIterator[_T]'
|
| async get_next_page(self: 'AsyncPageT') -> 'AsyncPageT'
|
| async iter_pages(self: 'AsyncPageT') -> 'AsyncIterator[AsyncPageT]'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BasePage:
|
| has_next_page(self) -> 'bool'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
class AsyncTokenPage(anthropic._base_client.BaseAsyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| AsyncTokenPage(**extra_data: Any) -> None
|
| Method resolution order:
| AsyncTokenPage
| anthropic._base_client.BaseAsyncPage[TypeVar]
| anthropic._base_client.BaseAsyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| has_next_page(self) -> bool
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'has_more': typing.Option...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseAsyncPage[TypeVar...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.AsyncT...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="AsyncTokenPage", valid...
|
| __signature__ = <Signature (*, data: List[~_T], has_more: Option...Opt...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseAsyncPage:
|
| async __aiter__(self) -> 'AsyncIterator[_T]'
|
| async get_next_page(self: 'AsyncPageT') -> 'AsyncPageT'
|
| async iter_pages(self: 'AsyncPageT') -> 'AsyncIterator[AsyncPageT]'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
class SyncBidirectionalPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| SyncBidirectionalPageCursor(**extra_data: Any) -> None
|
| Method resolution order:
| SyncBidirectionalPageCursor
| anthropic._base_client.BaseSyncPage[TypeVar]
| anthropic._base_client.BaseSyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'next_page': typing.Optio...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseSyncPage[TypeVar]...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.SyncBi...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="SyncBidirectionalPageC...
|
| __signature__ = <Signature (*, data: List[~_T], next_page: Optio...Opt...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseSyncPage:
|
| __iter__(self) -> 'Iterator[_T]'
| So `dict(model)` works.
|
| get_next_page(self: 'SyncPageT') -> 'SyncPageT'
|
| iter_pages(self: 'SyncPageT') -> 'Iterator[SyncPageT]'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BasePage:
|
| has_next_page(self) -> 'bool'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
class SyncPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| SyncPage(**extra_data: Any) -> None
|
| Method resolution order:
| SyncPage
| anthropic._base_client.BaseSyncPage[TypeVar]
| anthropic._base_client.BaseSyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| has_next_page(self) -> bool
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'first_id': typing.Option...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseSyncPage[TypeVar]...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.SyncPa...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="SyncPage", validator=M...
|
| __signature__ = <Signature (*, data: List[~_T], has_more: Option...Opt...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseSyncPage:
|
| __iter__(self) -> 'Iterator[_T]'
| So `dict(model)` works.
|
| get_next_page(self: 'SyncPageT') -> 'SyncPageT'
|
| iter_pages(self: 'SyncPageT') -> 'Iterator[SyncPageT]'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
class SyncPageCursor(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| SyncPageCursor(**extra_data: Any) -> None
|
| Method resolution order:
| SyncPageCursor
| anthropic._base_client.BaseSyncPage[TypeVar]
| anthropic._base_client.BaseSyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'next_page': typing.Optio...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseSyncPage[TypeVar]...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.SyncPa...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="SyncPageCursor", valid...
|
| __signature__ = <Signature (*, data: List[~_T], next_page: Optional[st...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseSyncPage:
|
| __iter__(self) -> 'Iterator[_T]'
| So `dict(model)` works.
|
| get_next_page(self: 'SyncPageT') -> 'SyncPageT'
|
| iter_pages(self: 'SyncPageT') -> 'Iterator[SyncPageT]'
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BasePage:
|
| has_next_page(self) -> 'bool'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
class SyncTokenPage(anthropic._base_client.BaseSyncPage[TypeVar], anthropic._base_client.BasePage[TypeVar], typing.Generic)
| SyncTokenPage(**extra_data: Any) -> None
|
| Method resolution order:
| SyncTokenPage
| anthropic._base_client.BaseSyncPage[TypeVar]
| anthropic._base_client.BaseSyncPage
| anthropic._base_client.BasePage[TypeVar]
| anthropic._base_client.BasePage
| anthropic._models.GenericModel
| anthropic._compat.GenericModel
| anthropic.BaseModel
| pydantic.main.BaseModel
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| has_next_page(self) -> bool
|
| model_post_init = init_private_attributes(self: 'BaseModel', context: 'Any', /) -> 'None' from pydantic._internal._model_construction
| This function is meant to behave like a BaseModel method to initialize private attributes.
|
| It takes context as an argument since that's what pydantic-core passes when calling it.
|
| Args:
| self: The BaseModel instance.
| context: The context.
|
| next_page_info(self) -> Optional[anthropic._base_client.PageInfo]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'data': typing.List[~_T], 'has_more': typing.Option...
|
| __class_vars__ = set()
|
| __orig_bases__ = (<class 'anthropic._base_client.BaseSyncPage[TypeVar]...
|
| __parameters__ = (~_T,)
|
| __private_attributes__ = {'_client': ModelPrivateAttr(default=Pydantic...
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'anthropic.pagination.SyncTo...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'data': FieldInfo(annotation=List[TypeVar], req...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = 'model_post_init'
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="SyncTokenPage", valida...
|
| __signature__ = <Signature (*, data: List[~_T], has_more: Option...Opt...
|
| model_config = {'defer_build': True, 'extra': 'allow'}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._base_client.BaseSyncPage:
|
| __iter__(self) -> 'Iterator[_T]'
| So `dict(model)` works.
|
| get_next_page(self: 'SyncPageT') -> 'SyncPageT'
|
| iter_pages(self: 'SyncPageT') -> 'Iterator[SyncPageT]'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._compat.GenericModel:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic.BaseModel:
|
| __str__(self) -> 'str' from anthropic._models.BaseModel
| Return str(self).
|
| to_dict(self, *, mode: "Literal['json', 'python']" = 'python', use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'dict[str, object]' from anthropic._models.BaseModel
| Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| mode:
| If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
| If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
|
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value from the output.
| exclude_none: Whether to exclude fields that have a value of `None` from the output.
| warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
|
| to_json(self, *, indent: 'int | None' = 2, use_api_names: 'bool' = True, exclude_unset: 'bool' = True, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, warnings: 'bool' = True) -> 'str' from anthropic._models.BaseModel
| Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
|
| By default, fields that were not set by the API will not be included,
| and keys will match the API response, *not* the property names from the model.
|
| For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
| the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
|
| Args:
| indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
| use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that have the default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
|
| ----------------------------------------------------------------------
| Class methods inherited from anthropic.BaseModel:
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| model_construct = construct(_fields_set: 'set[str] | None' = None, **values: 'object') -> 'ModelT' from anthropic._models.BaseModel
| # Override the 'construct' method in a way that supports recursive parsing without validation.
| # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'data': FieldInfo(annotation=List[TypeVar], required=T...
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
DATA
__all__ = ['SyncPage', 'AsyncPage', 'SyncTokenPage', 'AsyncTokenPage',...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\anthropic\pagination.py
anthropic.resources
Python Library Documentation: package anthropic.resources in anthropic
NAME
anthropic.resources - # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
PACKAGE CONTENTS
beta (package)
completions
messages (package)
models
CLASSES
anthropic._resource.AsyncAPIResource(builtins.object)
anthropic.resources.beta.beta.AsyncBeta
anthropic.resources.completions.AsyncCompletions
anthropic.resources.messages.messages.AsyncMessages
anthropic.resources.models.AsyncModels
anthropic._resource.SyncAPIResource(builtins.object)
anthropic.resources.beta.beta.Beta
anthropic.resources.completions.Completions
anthropic.resources.messages.messages.Messages
anthropic.resources.models.Models
builtins.object
anthropic.resources.beta.beta.AsyncBetaWithRawResponse
anthropic.resources.beta.beta.AsyncBetaWithStreamingResponse
anthropic.resources.beta.beta.BetaWithRawResponse
anthropic.resources.beta.beta.BetaWithStreamingResponse
anthropic.resources.completions.AsyncCompletionsWithRawResponse
anthropic.resources.completions.AsyncCompletionsWithStreamingResponse
anthropic.resources.completions.CompletionsWithRawResponse
anthropic.resources.completions.CompletionsWithStreamingResponse
anthropic.resources.messages.messages.AsyncMessagesWithRawResponse
anthropic.resources.messages.messages.AsyncMessagesWithStreamingResponse
anthropic.resources.messages.messages.MessagesWithRawResponse
anthropic.resources.messages.messages.MessagesWithStreamingResponse
anthropic.resources.models.AsyncModelsWithRawResponse
anthropic.resources.models.AsyncModelsWithStreamingResponse
anthropic.resources.models.ModelsWithRawResponse
anthropic.resources.models.ModelsWithStreamingResponse
class AsyncBeta(anthropic._resource.AsyncAPIResource)
| AsyncBeta(client: 'AsyncAPIClient') -> 'None'
|
| Method resolution order:
| AsyncBeta
| anthropic._resource.AsyncAPIResource
| builtins.object
|
| Methods defined here:
|
| agents = <functools.cached_property object>
| deployment_runs = <functools.cached_property object>
| deployments = <functools.cached_property object>
| dreams = <functools.cached_property object>
| environments = <functools.cached_property object>
| files = <functools.cached_property object>
| memory_stores = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| sessions = <functools.cached_property object>
| skills = <functools.cached_property object>
| tunnels = <functools.cached_property object>
| user_profiles = <functools.cached_property object>
| vaults = <functools.cached_property object>
| webhooks = <functools.cached_property object>
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.AsyncAPIResource:
|
| __init__(self, client: 'AsyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.AsyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncBetaWithRawResponse(builtins.object)
| AsyncBetaWithRawResponse(beta: 'AsyncBeta') -> 'None'
|
| Methods defined here:
|
| __init__(self, beta: 'AsyncBeta') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| agents = <functools.cached_property object>
| deployment_runs = <functools.cached_property object>
| deployments = <functools.cached_property object>
| dreams = <functools.cached_property object>
| environments = <functools.cached_property object>
| files = <functools.cached_property object>
| memory_stores = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| sessions = <functools.cached_property object>
| skills = <functools.cached_property object>
| tunnels = <functools.cached_property object>
| user_profiles = <functools.cached_property object>
| vaults = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncBetaWithStreamingResponse(builtins.object)
| AsyncBetaWithStreamingResponse(beta: 'AsyncBeta') -> 'None'
|
| Methods defined here:
|
| __init__(self, beta: 'AsyncBeta') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| agents = <functools.cached_property object>
| deployment_runs = <functools.cached_property object>
| deployments = <functools.cached_property object>
| dreams = <functools.cached_property object>
| environments = <functools.cached_property object>
| files = <functools.cached_property object>
| memory_stores = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| sessions = <functools.cached_property object>
| skills = <functools.cached_property object>
| tunnels = <functools.cached_property object>
| user_profiles = <functools.cached_property object>
| vaults = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncCompletions(anthropic._resource.AsyncAPIResource)
| AsyncCompletions(client: 'AsyncAPIClient') -> 'None'
|
| Method resolution order:
| AsyncCompletions
| anthropic._resource.AsyncAPIResource
| builtins.object
|
| Methods defined here:
|
| create(self, *, max_tokens_to_sample: 'int', model: 'ModelParam', prompt: 'str', metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stream: 'Literal[False] | Literal[True] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, betas: 'List[AnthropicBetaParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'Completion | AsyncStream[Completion]'
|
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.AsyncAPIResource:
|
| __init__(self, client: 'AsyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.AsyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncCompletionsWithRawResponse(builtins.object)
| AsyncCompletionsWithRawResponse(completions: 'AsyncCompletions') -> 'None'
|
| Methods defined here:
|
| __init__(self, completions: 'AsyncCompletions') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncCompletionsWithStreamingResponse(builtins.object)
| AsyncCompletionsWithStreamingResponse(completions: 'AsyncCompletions') -> 'None'
|
| Methods defined here:
|
| __init__(self, completions: 'AsyncCompletions') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncMessages(anthropic._resource.AsyncAPIResource)
| AsyncMessages(client: 'AsyncAPIClient') -> 'None'
|
| Method resolution order:
| AsyncMessages
| anthropic._resource.AsyncAPIResource
| builtins.object
|
| Methods defined here:
|
| batches = <functools.cached_property object>
| async count_tokens(self, *, messages: 'Iterable[MessageParam]', model: 'ModelParam', cache_control: 'Optional[CacheControlEphemeralParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_format: 'None | JSONOutputFormatParam | type | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[MessageCountTokensToolParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, user_profile_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'MessageTokensCount'
| Count the number of tokens in a Message.
|
| The Token Count API can be used to count the number of tokens in a Message,
| including tools, images, and documents, without creating it.
|
| Learn more about token counting in our
| [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
|
| Args:
| messages: Input messages.
|
| Our models are trained to operate on alternating `user` and `assistant`
| conversational turns. When creating a new `Message`, you specify the prior
| conversational turns with the `messages` parameter, and the model then generates
| the next `Message` in the conversation. Consecutive `user` or `assistant` turns
| in your request will be combined into a single turn.
|
| Each input message must be an object with a `role` and `content`. You can
| specify a single `user`-role message, or you can include multiple `user` and
| `assistant` messages.
|
| If the final message uses the `assistant` role, the response content will
| continue immediately from the content in that message. This can be used to
| constrain part of the model's response.
|
| Example with a single `user` message:
|
| ```json
| [{ "role": "user", "content": "Hello, Claude" }]
| ```
|
| Example with multiple conversational turns:
|
| ```json
| [
| { "role": "user", "content": "Hello there." },
| { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
| { "role": "user", "content": "Can you explain LLMs in plain English?" }
| ]
| ```
|
| Example with a partially-filled response from Claude:
|
| ```json
| [
| {
| "role": "user",
| "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
| },
| { "role": "assistant", "content": "The best answer is (" }
| ]
| ```
|
| Each input message `content` may be either a single `string` or an array of
| content blocks, where each block has a specific `type`. Using a `string` for
| `content` is shorthand for an array of one content block of type `"text"`. The
| following input messages are equivalent:
|
| ```json
| { "role": "user", "content": "Hello, Claude" }
| ```
|
| ```json
| { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
| ```
|
| See
| [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
|
| Note that if you want to include a
| [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
| 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 100,000 messages in a single request.
|
| model: The model that will complete your prompt.
|
| See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
| details and options.
|
| cache_control: Top-level cache control automatically applies a cache_control marker to the last
| cacheable block in the request.
|
| output_config: Configuration options for the model's output, such as the output format.
|
|
| system: System prompt.
|
| A system prompt is a way of providing context and instructions to Claude, such
| as specifying a particular goal or role. See our
| [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
|
| thinking: Configuration for enabling Claude's extended thinking.
|
| When enabled, responses include `thinking` content blocks showing Claude's
| thinking process before the final answer. Requires a minimum budget of 1,024
| tokens and counts towards your `max_tokens` limit.
|
| See
| [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
| for details.
|
| tool_choice: How the model should use the provided tools. The model can use a specific tool,
| any available tool, decide by itself, or not use tools at all.
|
| tools: Definitions of tools that the model may use.
|
| If you include `tools` in your API request, the model may return `tool_use`
| content blocks that represent the model's use of those tools. You can then run
| those tools using the tool input generated by the model and then optionally
| return results back to the model using `tool_result` content blocks.
|
| There are two types of tools: **client tools** and **server tools**. The
| behavior described below applies to client tools. For
| [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
| see their individual documentation as each has its own behavior (e.g., the
| [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
|
| Each tool definition includes:
|
| - `name`: Name of the tool.
| - `description`: Optional, but strongly-recommended description of the tool.
| - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
| tool `input` shape that the model will produce in `tool_use` output content
| blocks.
|
| For example, if you defined `tools` as:
|
| ```json
| [
| {
| "name": "get_stock_price",
| "description": "Get the current stock price for a given ticker symbol.",
| "input_schema": {
| "type": "object",
| "properties": {
| "ticker": {
| "type": "string",
| "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
| }
| },
| "required": ["ticker"]
| }
| }
| ]
| ```
|
| And then asked the model "What's the S&P 500 at today?", the model might produce
| `tool_use` content blocks in the response like this:
|
| ```json
| [
| {
| "type": "tool_use",
| "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
| "name": "get_stock_price",
| "input": { "ticker": "^GSPC" }
| }
| ]
| ```
|
| You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
| input, and return the following back to the model in a subsequent `user`
| message:
|
| ```json
| [
| {
| "type": "tool_result",
| "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
| "content": "259.75 USD"
| }
| ]
| ```
|
| Tools can be used for workflows that include running client-side tools and
| functions, or more generally whenever you want the model to produce a particular
| JSON structure of output.
|
| See our
| [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
| for more details.
|
| user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
| party other than your organization. Requires the `user-profiles` beta header.
|
| extra_headers: Send extra headers
|
| extra_query: Add additional query parameters to the request
|
| extra_body: Add additional JSON properties to the request
|
| timeout: Override the client-level default timeout for this request, in seconds
|
| create(self, *, max_tokens: 'int', messages: 'Iterable[MessageParam]', model: 'ModelParam', cache_control: 'Optional[CacheControlEphemeralParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, container: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, inference_geo: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, service_tier: "Literal['auto', 'standard_only'] | Omit" = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stream: 'Literal[False] | Literal[True] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[ToolUnionParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, user_profile_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'Message | AsyncStream[RawMessageStreamEvent]'
|
| async parse(self, *, max_tokens: 'int', messages: 'Iterable[MessageParam]', model: 'ModelParam', metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_format: 'Optional[type[ResponseFormatT]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, service_tier: "Literal['auto', 'standard_only'] | Omit" = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stream: 'Literal[False] | Literal[True] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[ToolUnionParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'ParsedMessage[ResponseFormatT]'
|
| stream(self, *, max_tokens: 'int', messages: 'Iterable[MessageParam]', model: 'ModelParam', cache_control: 'Optional[CacheControlEphemeralParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, inference_geo: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_format: 'None | JSONOutputFormatParam | type[ResponseFormatT] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, container: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, service_tier: "Literal['auto', 'standard_only'] | Omit" = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[ToolUnionParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, user_profile_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'AsyncMessageStreamManager[ResponseFormatT]'
| Create a Message stream
|
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.AsyncAPIResource:
|
| __init__(self, client: 'AsyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.AsyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncMessagesWithRawResponse(builtins.object)
| AsyncMessagesWithRawResponse(messages: 'AsyncMessages') -> 'None'
|
| Methods defined here:
|
| __init__(self, messages: 'AsyncMessages') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| batches = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncMessagesWithStreamingResponse(builtins.object)
| AsyncMessagesWithStreamingResponse(messages: 'AsyncMessages') -> 'None'
|
| Methods defined here:
|
| __init__(self, messages: 'AsyncMessages') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| batches = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncModels(anthropic._resource.AsyncAPIResource)
| AsyncModels(client: 'AsyncAPIClient') -> 'None'
|
| Method resolution order:
| AsyncModels
| anthropic._resource.AsyncAPIResource
| builtins.object
|
| Methods defined here:
|
| list(self, *, after_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, before_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, limit: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, betas: 'List[AnthropicBetaParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'AsyncPaginator[ModelInfo, AsyncPage[ModelInfo]]'
| List available models.
|
| The Models API response can be used to determine which models are available for
| use in the API. More recently released models are listed first.
|
| Args:
| after_id: ID of the object to use as a cursor for pagination. When provided, returns the
| page of results immediately after this object.
|
| before_id: ID of the object to use as a cursor for pagination. When provided, returns the
| page of results immediately before this object.
|
| limit: Number of items to return per page.
|
| 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
|
| extra_body: Add additional JSON properties to the request
|
| timeout: Override the client-level default timeout for this request, in seconds
|
| async retrieve(self, model_id: 'str', *, betas: 'List[AnthropicBetaParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'ModelInfo'
| Get a specific model.
|
| The Models API response can be used to determine information about a specific
| model or resolve a model alias to a model ID.
|
| 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
|
| extra_body: Add additional JSON properties to the request
|
| timeout: Override the client-level default timeout for this request, in seconds
|
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.AsyncAPIResource:
|
| __init__(self, client: 'AsyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.AsyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncModelsWithRawResponse(builtins.object)
| AsyncModelsWithRawResponse(models: 'AsyncModels') -> 'None'
|
| Methods defined here:
|
| __init__(self, models: 'AsyncModels') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class AsyncModelsWithStreamingResponse(builtins.object)
| AsyncModelsWithStreamingResponse(models: 'AsyncModels') -> 'None'
|
| Methods defined here:
|
| __init__(self, models: 'AsyncModels') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Beta(anthropic._resource.SyncAPIResource)
| Beta(client: 'SyncAPIClient') -> 'None'
|
| Method resolution order:
| Beta
| anthropic._resource.SyncAPIResource
| builtins.object
|
| Methods defined here:
|
| agents = <functools.cached_property object>
| deployment_runs = <functools.cached_property object>
| deployments = <functools.cached_property object>
| dreams = <functools.cached_property object>
| environments = <functools.cached_property object>
| files = <functools.cached_property object>
| memory_stores = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| sessions = <functools.cached_property object>
| skills = <functools.cached_property object>
| tunnels = <functools.cached_property object>
| user_profiles = <functools.cached_property object>
| vaults = <functools.cached_property object>
| webhooks = <functools.cached_property object>
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.SyncAPIResource:
|
| __init__(self, client: 'SyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.SyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class BetaWithRawResponse(builtins.object)
| BetaWithRawResponse(beta: 'Beta') -> 'None'
|
| Methods defined here:
|
| __init__(self, beta: 'Beta') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| agents = <functools.cached_property object>
| deployment_runs = <functools.cached_property object>
| deployments = <functools.cached_property object>
| dreams = <functools.cached_property object>
| environments = <functools.cached_property object>
| files = <functools.cached_property object>
| memory_stores = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| sessions = <functools.cached_property object>
| skills = <functools.cached_property object>
| tunnels = <functools.cached_property object>
| user_profiles = <functools.cached_property object>
| vaults = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class BetaWithStreamingResponse(builtins.object)
| BetaWithStreamingResponse(beta: 'Beta') -> 'None'
|
| Methods defined here:
|
| __init__(self, beta: 'Beta') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| agents = <functools.cached_property object>
| deployment_runs = <functools.cached_property object>
| deployments = <functools.cached_property object>
| dreams = <functools.cached_property object>
| environments = <functools.cached_property object>
| files = <functools.cached_property object>
| memory_stores = <functools.cached_property object>
| messages = <functools.cached_property object>
| models = <functools.cached_property object>
| sessions = <functools.cached_property object>
| skills = <functools.cached_property object>
| tunnels = <functools.cached_property object>
| user_profiles = <functools.cached_property object>
| vaults = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Completions(anthropic._resource.SyncAPIResource)
| Completions(client: 'SyncAPIClient') -> 'None'
|
| Method resolution order:
| Completions
| anthropic._resource.SyncAPIResource
| builtins.object
|
| Methods defined here:
|
| create(self, *, max_tokens_to_sample: 'int', model: 'ModelParam', prompt: 'str', metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stream: 'Literal[False] | Literal[True] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, betas: 'List[AnthropicBetaParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'Completion | Stream[Completion]'
|
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.SyncAPIResource:
|
| __init__(self, client: 'SyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.SyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class CompletionsWithRawResponse(builtins.object)
| CompletionsWithRawResponse(completions: 'Completions') -> 'None'
|
| Methods defined here:
|
| __init__(self, completions: 'Completions') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class CompletionsWithStreamingResponse(builtins.object)
| CompletionsWithStreamingResponse(completions: 'Completions') -> 'None'
|
| Methods defined here:
|
| __init__(self, completions: 'Completions') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Messages(anthropic._resource.SyncAPIResource)
| Messages(client: 'SyncAPIClient') -> 'None'
|
| Method resolution order:
| Messages
| anthropic._resource.SyncAPIResource
| builtins.object
|
| Methods defined here:
|
| batches = <functools.cached_property object>
| count_tokens(self, *, messages: 'Iterable[MessageParam]', model: 'ModelParam', cache_control: 'Optional[CacheControlEphemeralParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_format: 'None | JSONOutputFormatParam | type | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[MessageCountTokensToolParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, user_profile_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'MessageTokensCount'
| Count the number of tokens in a Message.
|
| The Token Count API can be used to count the number of tokens in a Message,
| including tools, images, and documents, without creating it.
|
| Learn more about token counting in our
| [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
|
| Args:
| messages: Input messages.
|
| Our models are trained to operate on alternating `user` and `assistant`
| conversational turns. When creating a new `Message`, you specify the prior
| conversational turns with the `messages` parameter, and the model then generates
| the next `Message` in the conversation. Consecutive `user` or `assistant` turns
| in your request will be combined into a single turn.
|
| Each input message must be an object with a `role` and `content`. You can
| specify a single `user`-role message, or you can include multiple `user` and
| `assistant` messages.
|
| If the final message uses the `assistant` role, the response content will
| continue immediately from the content in that message. This can be used to
| constrain part of the model's response.
|
| Example with a single `user` message:
|
| ```json
| [{ "role": "user", "content": "Hello, Claude" }]
| ```
|
| Example with multiple conversational turns:
|
| ```json
| [
| { "role": "user", "content": "Hello there." },
| { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
| { "role": "user", "content": "Can you explain LLMs in plain English?" }
| ]
| ```
|
| Example with a partially-filled response from Claude:
|
| ```json
| [
| {
| "role": "user",
| "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
| },
| { "role": "assistant", "content": "The best answer is (" }
| ]
| ```
|
| Each input message `content` may be either a single `string` or an array of
| content blocks, where each block has a specific `type`. Using a `string` for
| `content` is shorthand for an array of one content block of type `"text"`. The
| following input messages are equivalent:
|
| ```json
| { "role": "user", "content": "Hello, Claude" }
| ```
|
| ```json
| { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
| ```
|
| See
| [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
|
| Note that if you want to include a
| [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
| 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 100,000 messages in a single request.
|
| model: The model that will complete your prompt.
|
| See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
| details and options.
|
| cache_control: Top-level cache control automatically applies a cache_control marker to the last
| cacheable block in the request.
|
| output_config: Configuration options for the model's output, such as the output format.
|
|
| system: System prompt.
|
| A system prompt is a way of providing context and instructions to Claude, such
| as specifying a particular goal or role. See our
| [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
|
| thinking: Configuration for enabling Claude's extended thinking.
|
| When enabled, responses include `thinking` content blocks showing Claude's
| thinking process before the final answer. Requires a minimum budget of 1,024
| tokens and counts towards your `max_tokens` limit.
|
| See
| [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
| for details.
|
| tool_choice: How the model should use the provided tools. The model can use a specific tool,
| any available tool, decide by itself, or not use tools at all.
|
| tools: Definitions of tools that the model may use.
|
| If you include `tools` in your API request, the model may return `tool_use`
| content blocks that represent the model's use of those tools. You can then run
| those tools using the tool input generated by the model and then optionally
| return results back to the model using `tool_result` content blocks.
|
| There are two types of tools: **client tools** and **server tools**. The
| behavior described below applies to client tools. For
| [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
| see their individual documentation as each has its own behavior (e.g., the
| [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
|
| Each tool definition includes:
|
| - `name`: Name of the tool.
| - `description`: Optional, but strongly-recommended description of the tool.
| - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
| tool `input` shape that the model will produce in `tool_use` output content
| blocks.
|
| For example, if you defined `tools` as:
|
| ```json
| [
| {
| "name": "get_stock_price",
| "description": "Get the current stock price for a given ticker symbol.",
| "input_schema": {
| "type": "object",
| "properties": {
| "ticker": {
| "type": "string",
| "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
| }
| },
| "required": ["ticker"]
| }
| }
| ]
| ```
|
| And then asked the model "What's the S&P 500 at today?", the model might produce
| `tool_use` content blocks in the response like this:
|
| ```json
| [
| {
| "type": "tool_use",
| "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
| "name": "get_stock_price",
| "input": { "ticker": "^GSPC" }
| }
| ]
| ```
|
| You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
| input, and return the following back to the model in a subsequent `user`
| message:
|
| ```json
| [
| {
| "type": "tool_result",
| "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
| "content": "259.75 USD"
| }
| ]
| ```
|
| Tools can be used for workflows that include running client-side tools and
| functions, or more generally whenever you want the model to produce a particular
| JSON structure of output.
|
| See our
| [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
| for more details.
|
| user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
| party other than your organization. Requires the `user-profiles` beta header.
|
| extra_headers: Send extra headers
|
| extra_query: Add additional query parameters to the request
|
| extra_body: Add additional JSON properties to the request
|
| timeout: Override the client-level default timeout for this request, in seconds
|
| create(self, *, max_tokens: 'int', messages: 'Iterable[MessageParam]', model: 'ModelParam', cache_control: 'Optional[CacheControlEphemeralParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, container: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, inference_geo: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, service_tier: "Literal['auto', 'standard_only'] | Omit" = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stream: 'Literal[False] | Literal[True] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[ToolUnionParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, user_profile_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'Message | Stream[RawMessageStreamEvent]'
|
| parse(self, *, max_tokens: 'int', messages: 'Iterable[MessageParam]', model: 'ModelParam', metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_format: 'Optional[type[ResponseFormatT]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, service_tier: "Literal['auto', 'standard_only'] | Omit" = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, stream: 'Literal[False] | Literal[True] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[ToolUnionParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'ParsedMessage[ResponseFormatT]'
|
| stream(self, *, max_tokens: 'int', messages: 'Iterable[MessageParam]', model: 'ModelParam', cache_control: 'Optional[CacheControlEphemeralParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, inference_geo: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, metadata: 'MetadataParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_config: 'OutputConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, output_format: 'None | JSONOutputFormatParam | type[ResponseFormatT] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, container: 'Optional[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, service_tier: "Literal['auto', 'standard_only'] | Omit" = <anthropic.Omit object at 0x000002A337F806E0>, stop_sequences: 'SequenceNotStr[str] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, system: 'Union[str, Iterable[TextBlockParam]] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, temperature: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_k: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, top_p: 'float | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, thinking: 'ThinkingConfigParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tool_choice: 'ToolChoiceParam | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, tools: 'Iterable[ToolUnionParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, user_profile_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'MessageStreamManager[ResponseFormatT]'
| Create a Message stream
|
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.SyncAPIResource:
|
| __init__(self, client: 'SyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.SyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class MessagesWithRawResponse(builtins.object)
| MessagesWithRawResponse(messages: 'Messages') -> 'None'
|
| Methods defined here:
|
| __init__(self, messages: 'Messages') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| batches = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class MessagesWithStreamingResponse(builtins.object)
| MessagesWithStreamingResponse(messages: 'Messages') -> 'None'
|
| Methods defined here:
|
| __init__(self, messages: 'Messages') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| batches = <functools.cached_property object>
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Models(anthropic._resource.SyncAPIResource)
| Models(client: 'SyncAPIClient') -> 'None'
|
| Method resolution order:
| Models
| anthropic._resource.SyncAPIResource
| builtins.object
|
| Methods defined here:
|
| list(self, *, after_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, before_id: 'str | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, limit: 'int | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, betas: 'List[AnthropicBetaParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'SyncPage[ModelInfo]'
| List available models.
|
| The Models API response can be used to determine which models are available for
| use in the API. More recently released models are listed first.
|
| Args:
| after_id: ID of the object to use as a cursor for pagination. When provided, returns the
| page of results immediately after this object.
|
| before_id: ID of the object to use as a cursor for pagination. When provided, returns the
| page of results immediately before this object.
|
| limit: Number of items to return per page.
|
| 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
|
| extra_body: Add additional JSON properties to the request
|
| timeout: Override the client-level default timeout for this request, in seconds
|
| retrieve(self, model_id: 'str', *, betas: 'List[AnthropicBetaParam] | Omit' = <anthropic.Omit object at 0x000002A337F806E0>, extra_headers: 'Headers | None' = None, extra_query: 'Query | None' = None, extra_body: 'Body | None' = None, timeout: 'float | httpx.Timeout | None | NotGiven' = NOT_GIVEN) -> 'ModelInfo'
| Get a specific model.
|
| The Models API response can be used to determine information about a specific
| model or resolve a model alias to a model ID.
|
| 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
|
| extra_body: Add additional JSON properties to the request
|
| timeout: Override the client-level default timeout for this request, in seconds
|
| with_raw_response = <functools.cached_property object>
| This property can be used as a prefix for any HTTP method call to return
| the raw response object instead of the parsed content.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
|
| with_streaming_response = <functools.cached_property object>
| An alternative to `.with_raw_response` that doesn't eagerly read the response body.
|
| For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from anthropic._resource.SyncAPIResource:
|
| __init__(self, client: 'SyncAPIClient') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from anthropic._resource.SyncAPIResource:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ModelsWithRawResponse(builtins.object)
| ModelsWithRawResponse(models: 'Models') -> 'None'
|
| Methods defined here:
|
| __init__(self, models: 'Models') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ModelsWithStreamingResponse(builtins.object)
| ModelsWithStreamingResponse(models: 'Models') -> 'None'
|
| Methods defined here:
|
| __init__(self, models: 'Models') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
__all__ = ['Completions', 'AsyncCompletions', 'CompletionsWithRawRespo...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\anthropic\resources\__init__.py
anthropic.transform_schema
Python Library Documentation: function transform_schema in module anthropic
transform_schema(json_schema: 'type[pydantic.BaseModel] | dict[str, Any]') -> 'dict[str, Any]'
Transforms a JSON schema to ensure it conforms to the API's expectations.
Args:
json_schema (Dict[str, Any]): The original JSON schema.
Returns:
The transformed JSON schema.
Examples:
>>> transform_schema(
... {
... "type": "integer",
... "minimum": 1,
... "maximum": 10,
... "description": "A number",
... }
... )
{'type': 'integer', 'description': 'A number
{minimum: 1, maximum: 10}'}
anthropic.types
Python Library Documentation: package anthropic.types in anthropic
NAME
anthropic.types - # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
PACKAGE CONTENTS
anthropic_beta_param
base64_image_source_param
base64_pdf_source
base64_pdf_source_param
bash_code_execution_output_block
bash_code_execution_output_block_param
bash_code_execution_result_block
bash_code_execution_result_block_param
bash_code_execution_tool_result_block
bash_code_execution_tool_result_block_param
bash_code_execution_tool_result_error
bash_code_execution_tool_result_error_code
bash_code_execution_tool_result_error_param
beta (package)
beta_api_error
beta_authentication_error
beta_billing_error
beta_error
beta_error_response
beta_gateway_timeout_error
beta_invalid_request_error
beta_not_found_error
beta_overloaded_error
beta_permission_error
beta_rate_limit_error
cache_control_ephemeral_param
cache_creation
capability_support
citation_char_location
citation_char_location_param
citation_content_block_location
citation_content_block_location_param
citation_page_location
citation_page_location_param
citation_search_result_location_param
citation_web_search_result_location_param
citations_config
citations_config_param
citations_delta
citations_search_result_location
citations_web_search_result_location
code_execution_output_block
code_execution_output_block_param
code_execution_result_block
code_execution_result_block_param
code_execution_tool_20250522_param
code_execution_tool_20250825_param
code_execution_tool_20260120_param
code_execution_tool_20260521_param
code_execution_tool_result_block
code_execution_tool_result_block_content
code_execution_tool_result_block_param
code_execution_tool_result_block_param_content_param
code_execution_tool_result_error
code_execution_tool_result_error_code
code_execution_tool_result_error_param
completion
completion_create_params
container
container_upload_block
container_upload_block_param
content_block
content_block_delta_event
content_block_param
content_block_source_content_param
content_block_source_param
content_block_start_event
content_block_stop_event
context_management_capability
direct_caller
direct_caller_param
document_block
document_block_param
effort_capability
encrypted_code_execution_result_block
encrypted_code_execution_result_block_param
image_block_param
input_json_delta
json_output_format_param
memory_tool_20250818_param
message
message_count_tokens_params
message_count_tokens_tool_param
message_create_params
message_delta_event
message_delta_usage
message_param
message_start_event
message_stop_event
message_stream_event
message_tokens_count
messages (package)
metadata_param
mid_conversation_system_block_param
model
model_capabilities
model_info
model_list_params
model_param
output_config_param
output_tokens_details
parsed_message
plain_text_source
plain_text_source_param
raw_content_block_delta
raw_content_block_delta_event
raw_content_block_start_event
raw_content_block_stop_event
raw_message_delta_event
raw_message_start_event
raw_message_stop_event
raw_message_stream_event
redacted_thinking_block
redacted_thinking_block_param
refusal_stop_details
search_result_block_param
server_tool_caller
server_tool_caller_20260120
server_tool_caller_20260120_param
server_tool_caller_param
server_tool_usage
server_tool_use_block
server_tool_use_block_param
shared (package)
signature_delta
stop_reason
text_block
text_block_param
text_citation
text_citation_param
text_delta
text_editor_code_execution_create_result_block
text_editor_code_execution_create_result_block_param
text_editor_code_execution_str_replace_result_block
text_editor_code_execution_str_replace_result_block_param
text_editor_code_execution_tool_result_block
text_editor_code_execution_tool_result_block_param
text_editor_code_execution_tool_result_error
text_editor_code_execution_tool_result_error_code
text_editor_code_execution_tool_result_error_param
text_editor_code_execution_view_result_block
text_editor_code_execution_view_result_block_param
thinking_block
thinking_block_param
thinking_capability
thinking_config_adaptive_param
thinking_config_disabled_param
thinking_config_enabled_param
thinking_config_param
thinking_delta
thinking_types
tool_bash_20250124_param
tool_choice_any_param
tool_choice_auto_param
tool_choice_none_param
tool_choice_param
tool_choice_tool_param
tool_param
tool_reference_block
tool_reference_block_param
tool_result_block_param
tool_search_tool_bm25_20251119_param
tool_search_tool_regex_20251119_param
tool_search_tool_result_block
tool_search_tool_result_block_param
tool_search_tool_result_error
tool_search_tool_result_error_code
tool_search_tool_result_error_param
tool_search_tool_search_result_block
tool_search_tool_search_result_block_param
tool_text_editor_20250124_param
tool_text_editor_20250429_param
tool_text_editor_20250728_param
tool_union_param
tool_use_block
tool_use_block_param
url_image_source_param
url_pdf_source_param
usage
user_location_param
web_fetch_block
web_fetch_block_param
web_fetch_tool_20250910_param
web_fetch_tool_20260209_param
web_fetch_tool_20260309_param
web_fetch_tool_20260318_param
web_fetch_tool_result_block
web_fetch_tool_result_block_param
web_fetch_tool_result_error_block
web_fetch_tool_result_error_block_param
web_fetch_tool_result_error_code
web_search_result_block
web_search_result_block_param
web_search_tool_20250305_param
web_search_tool_20260209_param
web_search_tool_20260318_param
web_search_tool_request_error_param
web_search_tool_result_block
web_search_tool_result_block_content
web_search_tool_result_block_param
web_search_tool_result_block_param_content_param
web_search_tool_result_error
web_search_tool_result_error_code
DATA
AnthropicBetaParam = typing.Union[str, typing.Literal['message-batche....
BashCodeExecutionToolResultErrorCode = typing.Literal['invalid_tool_in...
BetaError = typing.Annotated[typing.Union[anthropic.types.be...e, form...
CodeExecutionToolResultBlockContent = typing.Union[anthropic.types.cod...
CodeExecutionToolResultBlockParamContentParam = typing.Union[anthropic...
CodeExecutionToolResultErrorCode = typing.Literal['invalid_tool_input'...
CompletionCreateParams = typing.Union[anthropic.types.completion_creat...
ContentBlock = typing.Annotated[typing.Union[anthropic.types.te...e, f...
ContentBlockParam = typing.Union[anthropic.types.text_block_param.Te.....
ContentBlockSourceContentParam = typing.Union[anthropic.types.text_blo...
ErrorObject = typing.Annotated[typing.Union[anthropic.types.sh...e, fo...
ErrorType = typing.Literal['invalid_request_error', 'authent...'overlo...
MessageCountTokensToolParam = typing.Union[anthropic.types.tool_param....
MessageCreateParams = typing.Union[anthropic.types.message_create_para...
MessageStreamEvent = typing.Annotated[typing.Union[anthropic.types.ra....
Model = typing.Union[typing.Literal['claude-sonnet-5', '...aude-opus-4...
ModelParam = typing.Union[typing.Literal['claude-sonnet-5', '...aude-o...
ParsedContentBlock = typing.Annotated[typing.Union[anthropic.types.pa....
RawContentBlockDelta = typing.Annotated[typing.Union[anthropic.types.t...
RawMessageStreamEvent = typing.Annotated[typing.Union[anthropic.types....
StopReason = typing.Literal['end_turn', 'max_tokens', 'stop_s...urn', ...
TextCitation = typing.Annotated[typing.Union[anthropic.types.ci...e, f...
TextCitationParam = typing.Union[anthropic.types.citation_char_locat.....
TextEditorCodeExecutionToolResultErrorCode = typing.Literal['invalid_t...
ThinkingConfigParam = typing.Union[anthropic.types.thinking_config_ena...
ToolChoiceParam = typing.Union[anthropic.types.tool_choice_auto_pa...t...
ToolSearchToolResultErrorCode = typing.Literal['invalid_tool_input', '...
ToolUnionParam = typing.Union[anthropic.types.tool_param.ToolPara..._2...
WebFetchToolResultErrorCode = typing.Literal['invalid_tool_input', 'ur...
WebSearchToolResultBlockContent = typing.Union[anthropic.types.web_sea...
WebSearchToolResultBlockParamContentParam = typing.Union[typing.Iterab...
WebSearchToolResultErrorCode = typing.Literal['invalid_tool_input', 'u...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\anthropic\types\__init__.py