From d81d1ec4fe56a7761fd5c3ad2afc65e8b12954fd Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 21 Aug 2025 19:30:40 +0000 Subject: [PATCH 01/17] chore: update github action --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index beb8dd8c..d85cbb49 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,7 +36,7 @@ jobs: run: ./scripts/lint build: - if: github.repository == 'stainless-sdks/writer-python' && (github.event_name == 'push' || github.event.pull_request.head.repo.fork) + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork timeout-minutes: 10 name: build permissions: @@ -61,12 +61,14 @@ jobs: run: rye build - name: Get GitHub OIDC Token + if: github.repository == 'stainless-sdks/writer-python' id: github-oidc uses: actions/github-script@v6 with: script: core.setOutput('github_token', await core.getIDToken()); - name: Upload tarball + if: github.repository == 'stainless-sdks/writer-python' env: URL: https://pkg.stainless.com/s AUTH: ${{ steps.github-oidc.outputs.github_token }} From 84dcbedf80ab51ed3d4379839682b0c584041bb9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 25 Aug 2025 22:26:10 +0000 Subject: [PATCH 02/17] chore(internal): change ci workflow machines --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d85cbb49..b1e32a40 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,7 +42,7 @@ jobs: permissions: contents: read id-token: write - runs-on: depot-ubuntu-24.04 + runs-on: ${{ github.repository == 'stainless-sdks/writer-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} steps: - uses: actions/checkout@v4 From 4aec5902d7329039817f2049c299458fa8eb1381 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 26 Aug 2025 16:03:16 +0000 Subject: [PATCH 03/17] fix: avoid newer type syntax --- src/writerai/_models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/writerai/_models.py b/src/writerai/_models.py index 486b948c..761b3b28 100644 --- a/src/writerai/_models.py +++ b/src/writerai/_models.py @@ -305,7 +305,7 @@ def model_dump( exclude_none=exclude_none, ) - return cast(dict[str, Any], json_safe(dumped)) if mode == "json" else dumped + return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped @override def model_dump_json( From 815b794df77ae9e20842db345988c93f1f077ee7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 26 Aug 2025 21:55:42 +0000 Subject: [PATCH 04/17] chore(internal): update pyright exclude list --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index e15a9eab..2278b83a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -151,6 +151,7 @@ exclude = [ "_dev", ".venv", ".nox", + ".git", ] reportImplicitOverride = true From 40901e2ad2c45f6d8258df2e0666cc88c6c1fa0f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 29 Aug 2025 19:19:34 +0000 Subject: [PATCH 05/17] chore(internal): add Sequence related utils --- src/writerai/_types.py | 36 ++++++++++++++++++++++++++++++++- src/writerai/_utils/__init__.py | 1 + src/writerai/_utils/_typing.py | 5 +++++ tests/utils.py | 10 ++++++++- 4 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/writerai/_types.py b/src/writerai/_types.py index cb87a472..31170df3 100644 --- a/src/writerai/_types.py +++ b/src/writerai/_types.py @@ -13,10 +13,21 @@ Mapping, TypeVar, Callable, + Iterator, Optional, Sequence, ) -from typing_extensions import Set, Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable +from typing_extensions import ( + Set, + Literal, + Protocol, + TypeAlias, + TypedDict, + SupportsIndex, + overload, + override, + runtime_checkable, +) import httpx import pydantic @@ -217,3 +228,26 @@ class _GenericAlias(Protocol): class HttpxSendArgs(TypedDict, total=False): auth: httpx.Auth follow_redirects: bool + + +_T_co = TypeVar("_T_co", covariant=True) + + +if TYPE_CHECKING: + # This works because str.__contains__ does not accept object (either in typeshed or at runtime) + # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285 + class SequenceNotStr(Protocol[_T_co]): + @overload + def __getitem__(self, index: SupportsIndex, /) -> _T_co: ... + @overload + def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ... + def __contains__(self, value: object, /) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T_co]: ... + def index(self, value: Any, start: int = 0, stop: int = ..., /) -> int: ... + def count(self, value: Any, /) -> int: ... + def __reversed__(self) -> Iterator[_T_co]: ... +else: + # just point this to a normal `Sequence` at runtime to avoid having to special case + # deserializing our custom sequence type + SequenceNotStr = Sequence diff --git a/src/writerai/_utils/__init__.py b/src/writerai/_utils/__init__.py index d4fda26f..ca547ce5 100644 --- a/src/writerai/_utils/__init__.py +++ b/src/writerai/_utils/__init__.py @@ -38,6 +38,7 @@ extract_type_arg as extract_type_arg, is_iterable_type as is_iterable_type, is_required_type as is_required_type, + is_sequence_type as is_sequence_type, is_annotated_type as is_annotated_type, is_type_alias_type as is_type_alias_type, strip_annotated_type as strip_annotated_type, diff --git a/src/writerai/_utils/_typing.py b/src/writerai/_utils/_typing.py index 1bac9542..845cd6b2 100644 --- a/src/writerai/_utils/_typing.py +++ b/src/writerai/_utils/_typing.py @@ -26,6 +26,11 @@ def is_list_type(typ: type) -> bool: return (get_origin(typ) or typ) == list +def is_sequence_type(typ: type) -> bool: + origin = get_origin(typ) or typ + return origin == typing_extensions.Sequence or origin == typing.Sequence or origin == _c_abc.Sequence + + def is_iterable_type(typ: type) -> bool: """If the given type is `typing.Iterable[T]`""" origin = get_origin(typ) or typ diff --git a/tests/utils.py b/tests/utils.py index 8d8f1908..b2f324aa 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -5,7 +5,7 @@ import inspect import traceback import contextlib -from typing import Any, TypeVar, Iterator, cast +from typing import Any, TypeVar, Iterator, Sequence, cast from datetime import date, datetime from typing_extensions import Literal, get_args, get_origin, assert_type @@ -18,6 +18,7 @@ is_list_type, is_union_type, extract_type_arg, + is_sequence_type, is_annotated_type, is_type_alias_type, ) @@ -74,6 +75,13 @@ def assert_matches_type( if is_list_type(type_): return _assert_list_type(type_, value) + if is_sequence_type(type_): + assert isinstance(value, Sequence) + inner_type = get_args(type_)[0] + for entry in value: # type: ignore + assert_type(inner_type, entry) # type: ignore + return + if origin == str: assert isinstance(value, str) elif origin == int: From 2c1a7de9a61c13b20b7734ba4f87da6ca7771e30 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Sep 2025 15:15:25 +0000 Subject: [PATCH 06/17] feat(types): replace List[str] with SequenceNotStr in params --- src/writerai/_utils/_transform.py | 6 ++++++ src/writerai/resources/applications/graphs.py | 8 +++----- src/writerai/resources/chat.py | 20 +++++++++---------- src/writerai/resources/completions.py | 20 +++++++++---------- src/writerai/resources/files.py | 7 +++---- src/writerai/resources/graphs.py | 20 +++++++++---------- src/writerai/resources/tools/tools.py | 12 +++++------ .../application_generate_content_params.py | 6 ++++-- .../types/applications/graph_update_params.py | 5 +++-- .../types/applications/job_create_params.py | 6 ++++-- src/writerai/types/chat_chat_params.py | 5 +++-- .../types/completion_create_params.py | 6 ++++-- src/writerai/types/file_retry_params.py | 5 +++-- src/writerai/types/graph_question_params.py | 6 ++++-- src/writerai/types/graph_update_params.py | 6 ++++-- .../types/shared_params/tool_param.py | 9 +++++---- src/writerai/types/tool_web_search_params.py | 8 +++++--- 17 files changed, 87 insertions(+), 68 deletions(-) diff --git a/src/writerai/_utils/_transform.py b/src/writerai/_utils/_transform.py index b0cc20a7..f0bcefd4 100644 --- a/src/writerai/_utils/_transform.py +++ b/src/writerai/_utils/_transform.py @@ -16,6 +16,7 @@ lru_cache, is_mapping, is_iterable, + is_sequence, ) from .._files import is_base64_file_input from ._typing import ( @@ -24,6 +25,7 @@ extract_type_arg, is_iterable_type, is_required_type, + is_sequence_type, is_annotated_type, strip_annotated_type, ) @@ -184,6 +186,8 @@ def _transform_recursive( (is_list_type(stripped_type) and is_list(data)) # Iterable[T] or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + # Sequence[T] + or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str)) ): # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually # intended as an iterable, so we don't transform it. @@ -346,6 +350,8 @@ async def _async_transform_recursive( (is_list_type(stripped_type) and is_list(data)) # Iterable[T] or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + # Sequence[T] + or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str)) ): # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually # intended as an iterable, so we don't transform it. diff --git a/src/writerai/resources/applications/graphs.py b/src/writerai/resources/applications/graphs.py index 9ab86c4e..cff8d7c6 100644 --- a/src/writerai/resources/applications/graphs.py +++ b/src/writerai/resources/applications/graphs.py @@ -2,11 +2,9 @@ from __future__ import annotations -from typing import List - import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, SequenceNotStr from ..._utils import maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource @@ -47,7 +45,7 @@ def update( self, application_id: str, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -141,7 +139,7 @@ async def update( self, application_id: str, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/writerai/resources/chat.py b/src/writerai/resources/chat.py index c6b0b0a5..dd18cf45 100644 --- a/src/writerai/resources/chat.py +++ b/src/writerai/resources/chat.py @@ -2,14 +2,14 @@ from __future__ import annotations -from typing import List, Type, Union, TypeVar, Iterable +from typing import Type, Union, TypeVar, Iterable from functools import partial from typing_extensions import Literal, overload import httpx from ..types import chat_chat_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, SequenceNotStr from .._utils import required_args, maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource @@ -68,7 +68,7 @@ def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, @@ -176,7 +176,7 @@ def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, @@ -283,7 +283,7 @@ def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, @@ -389,7 +389,7 @@ def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, @@ -642,7 +642,7 @@ async def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, @@ -750,7 +750,7 @@ async def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, @@ -857,7 +857,7 @@ async def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, @@ -963,7 +963,7 @@ async def chat( max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, response_format: chat_chat_params.ResponseFormat | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, diff --git a/src/writerai/resources/completions.py b/src/writerai/resources/completions.py index 081ec326..417eecc9 100644 --- a/src/writerai/resources/completions.py +++ b/src/writerai/resources/completions.py @@ -2,13 +2,13 @@ from __future__ import annotations -from typing import List, Union +from typing import Union from typing_extensions import Literal, overload import httpx from ..types import completion_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, SequenceNotStr from .._utils import required_args, maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource @@ -55,7 +55,7 @@ def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, @@ -121,7 +121,7 @@ def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -186,7 +186,7 @@ def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -250,7 +250,7 @@ def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, @@ -317,7 +317,7 @@ async def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, @@ -383,7 +383,7 @@ async def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -448,7 +448,7 @@ async def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -512,7 +512,7 @@ async def create( best_of: int | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, random_seed: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, top_p: float | NotGiven = NOT_GIVEN, diff --git a/src/writerai/resources/files.py b/src/writerai/resources/files.py index f77c4709..60f47979 100644 --- a/src/writerai/resources/files.py +++ b/src/writerai/resources/files.py @@ -2,13 +2,12 @@ from __future__ import annotations -from typing import List from typing_extensions import Literal import httpx from ..types import file_list_params, file_retry_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes, SequenceNotStr from .._utils import maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource @@ -236,7 +235,7 @@ def download( def retry( self, *, - file_ids: List[str], + file_ids: SequenceNotStr[str], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -512,7 +511,7 @@ async def download( async def retry( self, *, - file_ids: List[str], + file_ids: SequenceNotStr[str], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/writerai/resources/graphs.py b/src/writerai/resources/graphs.py index dc9b997d..85988d5d 100644 --- a/src/writerai/resources/graphs.py +++ b/src/writerai/resources/graphs.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Iterable +from typing import Iterable from typing_extensions import Literal, overload import httpx @@ -14,7 +14,7 @@ graph_question_params, graph_add_file_to_graph_params, ) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes, SequenceNotStr from .._utils import required_args, maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource @@ -358,7 +358,7 @@ def upload_and_add_file_to_graph( def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: Literal[False] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, @@ -397,7 +397,7 @@ def question( def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: Literal[True], subqueries: bool | NotGiven = NOT_GIVEN, @@ -436,7 +436,7 @@ def question( def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: bool, subqueries: bool | NotGiven = NOT_GIVEN, @@ -475,7 +475,7 @@ def question( def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, @@ -865,7 +865,7 @@ async def upload_and_add_file_to_graph( async def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: Literal[False] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, @@ -904,7 +904,7 @@ async def question( async def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: Literal[True], subqueries: bool | NotGiven = NOT_GIVEN, @@ -943,7 +943,7 @@ async def question( async def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: bool, subqueries: bool | NotGiven = NOT_GIVEN, @@ -982,7 +982,7 @@ async def question( async def question( self, *, - graph_ids: List[str], + graph_ids: SequenceNotStr[str], question: str, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, diff --git a/src/writerai/resources/tools/tools.py b/src/writerai/resources/tools/tools.py index cab8fb75..1f739424 100644 --- a/src/writerai/resources/tools/tools.py +++ b/src/writerai/resources/tools/tools.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union +from typing import Union from typing_extensions import Literal import httpx @@ -13,7 +13,7 @@ tool_web_search_params, tool_context_aware_splitting_params, ) -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, SequenceNotStr from ..._utils import maybe_transform, async_maybe_transform from ..._compat import cached_property from .comprehend import ( @@ -358,9 +358,9 @@ def web_search( ] | NotGiven = NOT_GIVEN, days: int | NotGiven = NOT_GIVEN, - exclude_domains: List[str] | NotGiven = NOT_GIVEN, + exclude_domains: SequenceNotStr[str] | NotGiven = NOT_GIVEN, include_answer: bool | NotGiven = NOT_GIVEN, - include_domains: List[str] | NotGiven = NOT_GIVEN, + include_domains: SequenceNotStr[str] | NotGiven = NOT_GIVEN, include_raw_content: Union[Literal["text", "markdown"], bool] | NotGiven = NOT_GIVEN, max_results: int | NotGiven = NOT_GIVEN, query: str | NotGiven = NOT_GIVEN, @@ -776,9 +776,9 @@ async def web_search( ] | NotGiven = NOT_GIVEN, days: int | NotGiven = NOT_GIVEN, - exclude_domains: List[str] | NotGiven = NOT_GIVEN, + exclude_domains: SequenceNotStr[str] | NotGiven = NOT_GIVEN, include_answer: bool | NotGiven = NOT_GIVEN, - include_domains: List[str] | NotGiven = NOT_GIVEN, + include_domains: SequenceNotStr[str] | NotGiven = NOT_GIVEN, include_raw_content: Union[Literal["text", "markdown"], bool] | NotGiven = NOT_GIVEN, max_results: int | NotGiven = NOT_GIVEN, query: str | NotGiven = NOT_GIVEN, diff --git a/src/writerai/types/application_generate_content_params.py b/src/writerai/types/application_generate_content_params.py index bfd7011c..401d52d4 100644 --- a/src/writerai/types/application_generate_content_params.py +++ b/src/writerai/types/application_generate_content_params.py @@ -2,9 +2,11 @@ from __future__ import annotations -from typing import List, Union, Iterable +from typing import Union, Iterable from typing_extensions import Literal, Required, TypedDict +from .._types import SequenceNotStr + __all__ = [ "ApplicationGenerateContentParamsBase", "Input", @@ -26,7 +28,7 @@ class Input(TypedDict, total=False): input type. """ - value: Required[List[str]] + value: Required[SequenceNotStr[str]] """The value for the input field. If the input type is "File upload", you must pass the `file_id` of an uploaded diff --git a/src/writerai/types/applications/graph_update_params.py b/src/writerai/types/applications/graph_update_params.py index 8a3bd87c..11fcf3bf 100644 --- a/src/writerai/types/applications/graph_update_params.py +++ b/src/writerai/types/applications/graph_update_params.py @@ -2,14 +2,15 @@ from __future__ import annotations -from typing import List from typing_extensions import Required, TypedDict +from ..._types import SequenceNotStr + __all__ = ["GraphUpdateParams"] class GraphUpdateParams(TypedDict, total=False): - graph_ids: Required[List[str]] + graph_ids: Required[SequenceNotStr[str]] """A list of Knowledge Graph IDs to associate with the application. Note that this will replace the existing list of Knowledge Graphs associated diff --git a/src/writerai/types/applications/job_create_params.py b/src/writerai/types/applications/job_create_params.py index 56c84c46..f3453a9f 100644 --- a/src/writerai/types/applications/job_create_params.py +++ b/src/writerai/types/applications/job_create_params.py @@ -2,9 +2,11 @@ from __future__ import annotations -from typing import List, Iterable +from typing import Iterable from typing_extensions import Required, TypedDict +from ..._types import SequenceNotStr + __all__ = ["JobCreateParams", "Input"] @@ -22,7 +24,7 @@ class Input(TypedDict, total=False): input type. """ - value: Required[List[str]] + value: Required[SequenceNotStr[str]] """The value for the input field. If the input type is "File upload", you must pass the `file_id` of an uploaded diff --git a/src/writerai/types/chat_chat_params.py b/src/writerai/types/chat_chat_params.py index e15fb942..522248af 100644 --- a/src/writerai/types/chat_chat_params.py +++ b/src/writerai/types/chat_chat_params.py @@ -2,9 +2,10 @@ from __future__ import annotations -from typing import List, Union, Iterable, Optional +from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict +from .._types import SequenceNotStr from .shared_params.tool_call import ToolCall from .shared_params.graph_data import GraphData from .shared_params.tool_param import ToolParam @@ -69,7 +70,7 @@ class ChatChatParamsBase(TypedDict, total=False): also provide a `json_schema` object. """ - stop: Union[List[str], str] + stop: Union[SequenceNotStr[str], str] """ A token or sequence of tokens that, when generated, will cause the model to stop producing further content. This can be a single token or an array of tokens, diff --git a/src/writerai/types/completion_create_params.py b/src/writerai/types/completion_create_params.py index b327c132..017e18bf 100644 --- a/src/writerai/types/completion_create_params.py +++ b/src/writerai/types/completion_create_params.py @@ -2,9 +2,11 @@ from __future__ import annotations -from typing import List, Union +from typing import Union from typing_extensions import Literal, Required, TypedDict +from .._types import SequenceNotStr + __all__ = ["CompletionCreateParamsBase", "CompletionCreateParamsNonStreaming", "CompletionCreateParamsStreaming"] @@ -35,7 +37,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): reproducibility of the output when the same inputs are provided. """ - stop: Union[List[str], str] + stop: Union[SequenceNotStr[str], str] """Specifies stopping conditions for the model's output generation. This can be an array of strings or a single string that the model will look for diff --git a/src/writerai/types/file_retry_params.py b/src/writerai/types/file_retry_params.py index 2f17762c..8882af6a 100644 --- a/src/writerai/types/file_retry_params.py +++ b/src/writerai/types/file_retry_params.py @@ -2,12 +2,13 @@ from __future__ import annotations -from typing import List from typing_extensions import Required, TypedDict +from .._types import SequenceNotStr + __all__ = ["FileRetryParams"] class FileRetryParams(TypedDict, total=False): - file_ids: Required[List[str]] + file_ids: Required[SequenceNotStr[str]] """The unique identifier of the files to retry.""" diff --git a/src/writerai/types/graph_question_params.py b/src/writerai/types/graph_question_params.py index b31390b6..02e8b513 100644 --- a/src/writerai/types/graph_question_params.py +++ b/src/writerai/types/graph_question_params.py @@ -2,14 +2,16 @@ from __future__ import annotations -from typing import List, Union +from typing import Union from typing_extensions import Literal, Required, TypedDict +from .._types import SequenceNotStr + __all__ = ["GraphQuestionParamsBase", "GraphQuestionParamsNonStreaming", "GraphQuestionParamsStreaming"] class GraphQuestionParamsBase(TypedDict, total=False): - graph_ids: Required[List[str]] + graph_ids: Required[SequenceNotStr[str]] """The unique identifiers of the Knowledge Graphs to query.""" question: Required[str] diff --git a/src/writerai/types/graph_update_params.py b/src/writerai/types/graph_update_params.py index 7be9324d..f400f902 100644 --- a/src/writerai/types/graph_update_params.py +++ b/src/writerai/types/graph_update_params.py @@ -2,9 +2,11 @@ from __future__ import annotations -from typing import List, Iterable +from typing import Iterable from typing_extensions import Literal, Required, TypedDict +from .._types import SequenceNotStr + __all__ = ["GraphUpdateParams", "URL"] @@ -36,5 +38,5 @@ class URL(TypedDict, total=False): url: Required[str] """The URL to be processed by the web connector.""" - exclude_urls: List[str] + exclude_urls: SequenceNotStr[str] """An array of URLs to exclude from processing within this web connector.""" diff --git a/src/writerai/types/shared_params/tool_param.py b/src/writerai/types/shared_params/tool_param.py index 25211144..677a33bd 100644 --- a/src/writerai/types/shared_params/tool_param.py +++ b/src/writerai/types/shared_params/tool_param.py @@ -2,9 +2,10 @@ from __future__ import annotations -from typing import List, Union, Iterable +from typing import Union, Iterable from typing_extensions import Literal, Required, TypeAlias, TypedDict +from ..._types import SequenceNotStr from .function_definition import FunctionDefinition __all__ = [ @@ -33,7 +34,7 @@ class FunctionTool(TypedDict, total=False): class GraphToolFunction(TypedDict, total=False): - graph_ids: Required[List[str]] + graph_ids: Required[SequenceNotStr[str]] """An array of graph IDs to use in the tool.""" subqueries: Required[bool] @@ -161,10 +162,10 @@ class VisionTool(TypedDict, total=False): class WebSearchToolFunction(TypedDict, total=False): - exclude_domains: Required[List[str]] + exclude_domains: Required[SequenceNotStr[str]] """An array of domains to exclude from the search results.""" - include_domains: Required[List[str]] + include_domains: Required[SequenceNotStr[str]] """An array of domains to include in the search results.""" diff --git a/src/writerai/types/tool_web_search_params.py b/src/writerai/types/tool_web_search_params.py index 800dc033..6f639e02 100644 --- a/src/writerai/types/tool_web_search_params.py +++ b/src/writerai/types/tool_web_search_params.py @@ -2,9 +2,11 @@ from __future__ import annotations -from typing import List, Union +from typing import Union from typing_extensions import Literal, TypedDict +from .._types import SequenceNotStr + __all__ = ["ToolWebSearchParams"] @@ -192,7 +194,7 @@ class ToolWebSearchParams(TypedDict, total=False): days: int """For news topic searches, specifies how many days of news coverage to include.""" - exclude_domains: List[str] + exclude_domains: SequenceNotStr[str] """Domains to exclude from the search. If unset, the search includes all domains.""" include_answer: bool @@ -201,7 +203,7 @@ class ToolWebSearchParams(TypedDict, total=False): If `false`, only search results are returned. """ - include_domains: List[str] + include_domains: SequenceNotStr[str] """Domains to include in the search. If unset, the search includes all domains.""" include_raw_content: Union[Literal["text", "markdown"], bool] From 74315c493b0f439614d492378ae34fc0728c8bb1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 3 Sep 2025 21:55:03 +0000 Subject: [PATCH 07/17] feat: improve future compat with pydantic v3 --- src/writerai/_base_client.py | 6 +- src/writerai/_compat.py | 96 ++++++++--------- src/writerai/_models.py | 80 +++++++------- src/writerai/_utils/__init__.py | 10 +- src/writerai/_utils/_compat.py | 45 ++++++++ src/writerai/_utils/_datetime_parse.py | 136 ++++++++++++++++++++++++ src/writerai/_utils/_transform.py | 6 +- src/writerai/_utils/_typing.py | 2 +- src/writerai/_utils/_utils.py | 1 - tests/test_models.py | 48 ++++----- tests/test_transform.py | 16 +-- tests/test_utils/test_datetime_parse.py | 110 +++++++++++++++++++ tests/utils.py | 8 +- 13 files changed, 432 insertions(+), 132 deletions(-) create mode 100644 src/writerai/_utils/_compat.py create mode 100644 src/writerai/_utils/_datetime_parse.py create mode 100644 tests/test_utils/test_datetime_parse.py diff --git a/src/writerai/_base_client.py b/src/writerai/_base_client.py index d1fb3996..a4c4b639 100644 --- a/src/writerai/_base_client.py +++ b/src/writerai/_base_client.py @@ -60,7 +60,7 @@ ModelBuilderProtocol, ) from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping -from ._compat import PYDANTIC_V2, model_copy, model_dump +from ._compat import PYDANTIC_V1, model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type from ._response import ( APIResponse, @@ -233,7 +233,7 @@ def _set_private_attributes( model: Type[_T], options: FinalRequestOptions, ) -> None: - if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: self.__pydantic_private__ = {} self._model = model @@ -321,7 +321,7 @@ def _set_private_attributes( client: AsyncAPIClient, options: FinalRequestOptions, ) -> None: - if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: self.__pydantic_private__ = {} self._model = model diff --git a/src/writerai/_compat.py b/src/writerai/_compat.py index 87fc3707..7d15e6b3 100644 --- a/src/writerai/_compat.py +++ b/src/writerai/_compat.py @@ -12,14 +12,13 @@ _T = TypeVar("_T") _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel) -# --------------- Pydantic v2 compatibility --------------- +# --------------- Pydantic v2, v3 compatibility --------------- # Pyright incorrectly reports some of our functions as overriding a method when they don't # pyright: reportIncompatibleMethodOverride=false -PYDANTIC_V2 = pydantic.VERSION.startswith("2.") +PYDANTIC_V1 = pydantic.VERSION.startswith("1.") -# v1 re-exports if TYPE_CHECKING: def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001 @@ -44,90 +43,92 @@ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 ... else: - if PYDANTIC_V2: - from pydantic.v1.typing import ( + # v1 re-exports + if PYDANTIC_V1: + from pydantic.typing import ( get_args as get_args, is_union as is_union, get_origin as get_origin, is_typeddict as is_typeddict, is_literal_type as is_literal_type, ) - from pydantic.v1.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime + from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime else: - from pydantic.typing import ( + from ._utils import ( get_args as get_args, is_union as is_union, get_origin as get_origin, + parse_date as parse_date, is_typeddict as is_typeddict, + parse_datetime as parse_datetime, is_literal_type as is_literal_type, ) - from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime # refactored config if TYPE_CHECKING: from pydantic import ConfigDict as ConfigDict else: - if PYDANTIC_V2: - from pydantic import ConfigDict - else: + if PYDANTIC_V1: # TODO: provide an error message here? ConfigDict = None + else: + from pydantic import ConfigDict as ConfigDict # renamed methods / properties def parse_obj(model: type[_ModelT], value: object) -> _ModelT: - if PYDANTIC_V2: - return model.model_validate(value) - else: + if PYDANTIC_V1: return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + else: + return model.model_validate(value) def field_is_required(field: FieldInfo) -> bool: - if PYDANTIC_V2: - return field.is_required() - return field.required # type: ignore + if PYDANTIC_V1: + return field.required # type: ignore + return field.is_required() def field_get_default(field: FieldInfo) -> Any: value = field.get_default() - if PYDANTIC_V2: - from pydantic_core import PydanticUndefined - - if value == PydanticUndefined: - return None + if PYDANTIC_V1: return value + from pydantic_core import PydanticUndefined + + if value == PydanticUndefined: + return None return value def field_outer_type(field: FieldInfo) -> Any: - if PYDANTIC_V2: - return field.annotation - return field.outer_type_ # type: ignore + if PYDANTIC_V1: + return field.outer_type_ # type: ignore + return field.annotation def get_model_config(model: type[pydantic.BaseModel]) -> Any: - if PYDANTIC_V2: - return model.model_config - return model.__config__ # type: ignore + if PYDANTIC_V1: + return model.__config__ # type: ignore + return model.model_config def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]: - if PYDANTIC_V2: - return model.model_fields - return model.__fields__ # type: ignore + if PYDANTIC_V1: + return model.__fields__ # type: ignore + return model.model_fields def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT: - if PYDANTIC_V2: - return model.model_copy(deep=deep) - return model.copy(deep=deep) # type: ignore + if PYDANTIC_V1: + return model.copy(deep=deep) # type: ignore + return model.model_copy(deep=deep) def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: - if PYDANTIC_V2: - return model.model_dump_json(indent=indent) - return model.json(indent=indent) # type: ignore + if PYDANTIC_V1: + return model.json(indent=indent) # type: ignore + return model.model_dump_json(indent=indent) def model_dump( @@ -139,14 +140,14 @@ def model_dump( warnings: bool = True, mode: Literal["json", "python"] = "python", ) -> dict[str, Any]: - if PYDANTIC_V2 or hasattr(model, "model_dump"): + if (not PYDANTIC_V1) or hasattr(model, "model_dump"): return model.model_dump( mode=mode, exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, # warnings are not supported in Pydantic v1 - warnings=warnings if PYDANTIC_V2 else True, + warnings=True if PYDANTIC_V1 else warnings, ) return cast( "dict[str, Any]", @@ -159,9 +160,9 @@ def model_dump( def model_parse(model: type[_ModelT], data: Any) -> _ModelT: - if PYDANTIC_V2: - return model.model_validate(data) - return model.parse_obj(data) # pyright: ignore[reportDeprecated] + if PYDANTIC_V1: + return model.parse_obj(data) # pyright: ignore[reportDeprecated] + return model.model_validate(data) def model_parse_json(model: type[_ModelT], data: str | bytes) -> _ModelT: @@ -182,17 +183,16 @@ def model_json_schema(model: type[_ModelT]) -> dict[str, Any]: class GenericModel(pydantic.BaseModel): ... else: - if PYDANTIC_V2: + if PYDANTIC_V1: + import pydantic.generics + + class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... + else: # there no longer needs to be a distinction in v2 but # we still have to create our own subclass to avoid # inconsistent MRO ordering errors class GenericModel(pydantic.BaseModel): ... - else: - import pydantic.generics - - class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... - # cached properties if TYPE_CHECKING: diff --git a/src/writerai/_models.py b/src/writerai/_models.py index 761b3b28..057a807f 100644 --- a/src/writerai/_models.py +++ b/src/writerai/_models.py @@ -51,7 +51,7 @@ strip_annotated_type, ) from ._compat import ( - PYDANTIC_V2, + PYDANTIC_V1, ConfigDict, GenericModel as BaseGenericModel, get_args, @@ -82,11 +82,7 @@ class _ConfigProtocol(Protocol): class BaseModel(pydantic.BaseModel): - if PYDANTIC_V2: - model_config: ClassVar[ConfigDict] = ConfigDict( - extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")) - ) - else: + if PYDANTIC_V1: @property @override @@ -96,6 +92,10 @@ def model_fields_set(self) -> set[str]: class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] extra: Any = pydantic.Extra.allow # type: ignore + else: + model_config: ClassVar[ConfigDict] = ConfigDict( + extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")) + ) def to_dict( self, @@ -216,25 +216,25 @@ def construct( # pyright: ignore[reportIncompatibleMethodOverride] if key not in model_fields: parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value - if PYDANTIC_V2: - _extra[key] = parsed - else: + if PYDANTIC_V1: _fields_set.add(key) fields_values[key] = parsed + else: + _extra[key] = parsed object.__setattr__(m, "__dict__", fields_values) - if PYDANTIC_V2: - # these properties are copied from Pydantic's `model_construct()` method - object.__setattr__(m, "__pydantic_private__", None) - object.__setattr__(m, "__pydantic_extra__", _extra) - object.__setattr__(m, "__pydantic_fields_set__", _fields_set) - else: + if PYDANTIC_V1: # init_private_attributes() does not exist in v2 m._init_private_attributes() # type: ignore # copied from Pydantic v1's `construct()` method object.__setattr__(m, "__fields_set__", _fields_set) + else: + # these properties are copied from Pydantic's `model_construct()` method + object.__setattr__(m, "__pydantic_private__", None) + object.__setattr__(m, "__pydantic_extra__", _extra) + object.__setattr__(m, "__pydantic_fields_set__", _fields_set) return m @@ -244,7 +244,7 @@ def construct( # pyright: ignore[reportIncompatibleMethodOverride] # although not in practice model_construct = construct - if not PYDANTIC_V2: + if PYDANTIC_V1: # we define aliases for some of the new pydantic v2 methods so # that we can just document these methods without having to specify # a specific pydantic version as some users may not know which @@ -364,10 +364,10 @@ def _construct_field(value: object, field: FieldInfo, key: str) -> object: if value is None: return field_get_default(field) - if PYDANTIC_V2: - type_ = field.annotation - else: + if PYDANTIC_V1: type_ = cast(type, field.outer_type_) # type: ignore + else: + type_ = field.annotation # type: ignore if type_ is None: raise RuntimeError(f"Unexpected field type is None for {key}") @@ -376,7 +376,7 @@ def _construct_field(value: object, field: FieldInfo, key: str) -> object: def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None: - if not PYDANTIC_V2: + if PYDANTIC_V1: # TODO return None @@ -629,30 +629,30 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, for variant in get_args(union): variant = strip_annotated_type(variant) if is_basemodel_type(variant): - if PYDANTIC_V2: - field = _extract_field_schema_pv2(variant, discriminator_field_name) - if not field: + if PYDANTIC_V1: + field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + if not field_info: continue # Note: if one variant defines an alias then they all should - discriminator_alias = field.get("serialization_alias") - - field_schema = field["schema"] + discriminator_alias = field_info.alias - if field_schema["type"] == "literal": - for entry in cast("LiteralSchema", field_schema)["expected"]: + if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): + for entry in get_args(annotation): if isinstance(entry, str): mapping[entry] = variant else: - field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] - if not field_info: + field = _extract_field_schema_pv2(variant, discriminator_field_name) + if not field: continue # Note: if one variant defines an alias then they all should - discriminator_alias = field_info.alias + discriminator_alias = field.get("serialization_alias") - if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): - for entry in get_args(annotation): + field_schema = field["schema"] + + if field_schema["type"] == "literal": + for entry in cast("LiteralSchema", field_schema)["expected"]: if isinstance(entry, str): mapping[entry] = variant @@ -715,7 +715,7 @@ class GenericModel(BaseGenericModel, BaseModel): pass -if PYDANTIC_V2: +if not PYDANTIC_V1: from pydantic import TypeAdapter as _TypeAdapter _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter)) @@ -785,12 +785,12 @@ class FinalRequestOptions(pydantic.BaseModel): json_data: Union[Body, None] = None extra_json: Union[AnyMapping, None] = None - if PYDANTIC_V2: - model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) - else: + if PYDANTIC_V1: class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] arbitrary_types_allowed: bool = True + else: + model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) def get_max_retries(self, max_retries: int) -> int: if isinstance(self.max_retries, NotGiven): @@ -823,9 +823,9 @@ def construct( # type: ignore key: strip_not_given(value) for key, value in values.items() } - if PYDANTIC_V2: - return super().model_construct(_fields_set, **kwargs) - return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated] + if PYDANTIC_V1: + return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated] + return super().model_construct(_fields_set, **kwargs) if not TYPE_CHECKING: # type checkers incorrectly complain about this assignment diff --git a/src/writerai/_utils/__init__.py b/src/writerai/_utils/__init__.py index ca547ce5..dc64e29a 100644 --- a/src/writerai/_utils/__init__.py +++ b/src/writerai/_utils/__init__.py @@ -10,7 +10,6 @@ lru_cache as lru_cache, is_mapping as is_mapping, is_tuple_t as is_tuple_t, - parse_date as parse_date, is_iterable as is_iterable, is_sequence as is_sequence, coerce_float as coerce_float, @@ -23,7 +22,6 @@ coerce_boolean as coerce_boolean, coerce_integer as coerce_integer, file_from_path as file_from_path, - parse_datetime as parse_datetime, strip_not_given as strip_not_given, deepcopy_minimal as deepcopy_minimal, get_async_library as get_async_library, @@ -32,6 +30,13 @@ maybe_coerce_boolean as maybe_coerce_boolean, maybe_coerce_integer as maybe_coerce_integer, ) +from ._compat import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, +) from ._typing import ( is_list_type as is_list_type, is_union_type as is_union_type, @@ -56,3 +61,4 @@ function_has_argument as function_has_argument, assert_signatures_in_sync as assert_signatures_in_sync, ) +from ._datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime diff --git a/src/writerai/_utils/_compat.py b/src/writerai/_utils/_compat.py new file mode 100644 index 00000000..dd703233 --- /dev/null +++ b/src/writerai/_utils/_compat.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import sys +import typing_extensions +from typing import Any, Type, Union, Literal, Optional +from datetime import date, datetime +from typing_extensions import get_args as _get_args, get_origin as _get_origin + +from .._types import StrBytesIntFloat +from ._datetime_parse import parse_date as _parse_date, parse_datetime as _parse_datetime + +_LITERAL_TYPES = {Literal, typing_extensions.Literal} + + +def get_args(tp: type[Any]) -> tuple[Any, ...]: + return _get_args(tp) + + +def get_origin(tp: type[Any]) -> type[Any] | None: + return _get_origin(tp) + + +def is_union(tp: Optional[Type[Any]]) -> bool: + if sys.version_info < (3, 10): + return tp is Union # type: ignore[comparison-overlap] + else: + import types + + return tp is Union or tp is types.UnionType + + +def is_typeddict(tp: Type[Any]) -> bool: + return typing_extensions.is_typeddict(tp) + + +def is_literal_type(tp: Type[Any]) -> bool: + return get_origin(tp) in _LITERAL_TYPES + + +def parse_date(value: Union[date, StrBytesIntFloat]) -> date: + return _parse_date(value) + + +def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: + return _parse_datetime(value) diff --git a/src/writerai/_utils/_datetime_parse.py b/src/writerai/_utils/_datetime_parse.py new file mode 100644 index 00000000..7cb9d9e6 --- /dev/null +++ b/src/writerai/_utils/_datetime_parse.py @@ -0,0 +1,136 @@ +""" +This file contains code from https://github.com/pydantic/pydantic/blob/main/pydantic/v1/datetime_parse.py +without the Pydantic v1 specific errors. +""" + +from __future__ import annotations + +import re +from typing import Dict, Union, Optional +from datetime import date, datetime, timezone, timedelta + +from .._types import StrBytesIntFloat + +date_expr = r"(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})" +time_expr = ( + r"(?P\d{1,2}):(?P\d{1,2})" + r"(?::(?P\d{1,2})(?:\.(?P\d{1,6})\d{0,6})?)?" + r"(?PZ|[+-]\d{2}(?::?\d{2})?)?$" +) + +date_re = re.compile(f"{date_expr}$") +datetime_re = re.compile(f"{date_expr}[T ]{time_expr}") + + +EPOCH = datetime(1970, 1, 1) +# if greater than this, the number is in ms, if less than or equal it's in seconds +# (in seconds this is 11th October 2603, in ms it's 20th August 1970) +MS_WATERSHED = int(2e10) +# slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9 +MAX_NUMBER = int(3e20) + + +def _get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[None, int, float]: + if isinstance(value, (int, float)): + return value + try: + return float(value) + except ValueError: + return None + except TypeError: + raise TypeError(f"invalid type; expected {native_expected_type}, string, bytes, int or float") from None + + +def _from_unix_seconds(seconds: Union[int, float]) -> datetime: + if seconds > MAX_NUMBER: + return datetime.max + elif seconds < -MAX_NUMBER: + return datetime.min + + while abs(seconds) > MS_WATERSHED: + seconds /= 1000 + dt = EPOCH + timedelta(seconds=seconds) + return dt.replace(tzinfo=timezone.utc) + + +def _parse_timezone(value: Optional[str]) -> Union[None, int, timezone]: + if value == "Z": + return timezone.utc + elif value is not None: + offset_mins = int(value[-2:]) if len(value) > 3 else 0 + offset = 60 * int(value[1:3]) + offset_mins + if value[0] == "-": + offset = -offset + return timezone(timedelta(minutes=offset)) + else: + return None + + +def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: + """ + Parse a datetime/int/float/string and return a datetime.datetime. + + This function supports time zone offsets. When the input contains one, + the output uses a timezone with a fixed offset from UTC. + + Raise ValueError if the input is well formatted but not a valid datetime. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, datetime): + return value + + number = _get_numeric(value, "datetime") + if number is not None: + return _from_unix_seconds(number) + + if isinstance(value, bytes): + value = value.decode() + + assert not isinstance(value, (float, int)) + + match = datetime_re.match(value) + if match is None: + raise ValueError("invalid datetime format") + + kw = match.groupdict() + if kw["microsecond"]: + kw["microsecond"] = kw["microsecond"].ljust(6, "0") + + tzinfo = _parse_timezone(kw.pop("tzinfo")) + kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} + kw_["tzinfo"] = tzinfo + + return datetime(**kw_) # type: ignore + + +def parse_date(value: Union[date, StrBytesIntFloat]) -> date: + """ + Parse a date/int/float/string and return a datetime.date. + + Raise ValueError if the input is well formatted but not a valid date. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, date): + if isinstance(value, datetime): + return value.date() + else: + return value + + number = _get_numeric(value, "date") + if number is not None: + return _from_unix_seconds(number).date() + + if isinstance(value, bytes): + value = value.decode() + + assert not isinstance(value, (float, int)) + match = date_re.match(value) + if match is None: + raise ValueError("invalid date format") + + kw = {k: int(v) for k, v in match.groupdict().items()} + + try: + return date(**kw) + except ValueError: + raise ValueError("invalid date format") from None diff --git a/src/writerai/_utils/_transform.py b/src/writerai/_utils/_transform.py index f0bcefd4..c19124f0 100644 --- a/src/writerai/_utils/_transform.py +++ b/src/writerai/_utils/_transform.py @@ -19,6 +19,7 @@ is_sequence, ) from .._files import is_base64_file_input +from ._compat import get_origin, is_typeddict from ._typing import ( is_list_type, is_union_type, @@ -29,7 +30,6 @@ is_annotated_type, strip_annotated_type, ) -from .._compat import get_origin, model_dump, is_typeddict _T = TypeVar("_T") @@ -169,6 +169,8 @@ def _transform_recursive( Defaults to the same value as the `annotation` argument. """ + from .._compat import model_dump + if inner_type is None: inner_type = annotation @@ -333,6 +335,8 @@ async def _async_transform_recursive( Defaults to the same value as the `annotation` argument. """ + from .._compat import model_dump + if inner_type is None: inner_type = annotation diff --git a/src/writerai/_utils/_typing.py b/src/writerai/_utils/_typing.py index 845cd6b2..193109f3 100644 --- a/src/writerai/_utils/_typing.py +++ b/src/writerai/_utils/_typing.py @@ -15,7 +15,7 @@ from ._utils import lru_cache from .._types import InheritsGeneric -from .._compat import is_union as _is_union +from ._compat import is_union as _is_union def is_annotated_type(typ: type) -> bool: diff --git a/src/writerai/_utils/_utils.py b/src/writerai/_utils/_utils.py index ea3cf3f2..f0818595 100644 --- a/src/writerai/_utils/_utils.py +++ b/src/writerai/_utils/_utils.py @@ -22,7 +22,6 @@ import sniffio from .._types import NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import parse_date as parse_date, parse_datetime as parse_datetime _T = TypeVar("_T") _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) diff --git a/tests/test_models.py b/tests/test_models.py index 0bf7e815..af9b6e48 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -8,7 +8,7 @@ from pydantic import Field from writerai._utils import PropertyInfo -from writerai._compat import PYDANTIC_V2, parse_obj, model_dump, model_json +from writerai._compat import PYDANTIC_V1, parse_obj, model_dump, model_json from writerai._models import BaseModel, construct_type @@ -294,12 +294,12 @@ class Model(BaseModel): assert cast(bool, m.foo) is True m = Model.construct(foo={"name": 3}) - if PYDANTIC_V2: - assert isinstance(m.foo, Submodel1) - assert m.foo.name == 3 # type: ignore - else: + if PYDANTIC_V1: assert isinstance(m.foo, Submodel2) assert m.foo.name == "3" + else: + assert isinstance(m.foo, Submodel1) + assert m.foo.name == 3 # type: ignore def test_list_of_unions() -> None: @@ -426,10 +426,10 @@ class Model(BaseModel): expected = datetime(2019, 12, 27, 18, 11, 19, 117000, tzinfo=timezone.utc) - if PYDANTIC_V2: - expected_json = '{"created_at":"2019-12-27T18:11:19.117000Z"}' - else: + if PYDANTIC_V1: expected_json = '{"created_at": "2019-12-27T18:11:19.117000+00:00"}' + else: + expected_json = '{"created_at":"2019-12-27T18:11:19.117000Z"}' model = Model.construct(created_at="2019-12-27T18:11:19.117Z") assert model.created_at == expected @@ -531,7 +531,7 @@ class Model2(BaseModel): assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)} assert m4.to_dict(mode="json") == {"created_at": time_str} - if not PYDANTIC_V2: + if PYDANTIC_V1: with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): m.to_dict(warnings=False) @@ -556,7 +556,7 @@ class Model(BaseModel): assert m3.model_dump() == {"foo": None} assert m3.model_dump(exclude_none=True) == {} - if not PYDANTIC_V2: + if PYDANTIC_V1: with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"): m.model_dump(round_trip=True) @@ -580,10 +580,10 @@ class Model(BaseModel): assert json.loads(m.to_json()) == {"FOO": "hello"} assert json.loads(m.to_json(use_api_names=False)) == {"foo": "hello"} - if PYDANTIC_V2: - assert m.to_json(indent=None) == '{"FOO":"hello"}' - else: + if PYDANTIC_V1: assert m.to_json(indent=None) == '{"FOO": "hello"}' + else: + assert m.to_json(indent=None) == '{"FOO":"hello"}' m2 = Model() assert json.loads(m2.to_json()) == {} @@ -595,7 +595,7 @@ class Model(BaseModel): assert json.loads(m3.to_json()) == {"FOO": None} assert json.loads(m3.to_json(exclude_none=True)) == {} - if not PYDANTIC_V2: + if PYDANTIC_V1: with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): m.to_json(warnings=False) @@ -622,7 +622,7 @@ class Model(BaseModel): assert json.loads(m3.model_dump_json()) == {"foo": None} assert json.loads(m3.model_dump_json(exclude_none=True)) == {} - if not PYDANTIC_V2: + if PYDANTIC_V1: with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"): m.model_dump_json(round_trip=True) @@ -679,12 +679,12 @@ class B(BaseModel): ) assert isinstance(m, A) assert m.type == "a" - if PYDANTIC_V2: - assert m.data == 100 # type: ignore[comparison-overlap] - else: + if PYDANTIC_V1: # pydantic v1 automatically converts inputs to strings # if the expected type is a str assert m.data == "100" + else: + assert m.data == 100 # type: ignore[comparison-overlap] def test_discriminated_unions_unknown_variant() -> None: @@ -768,12 +768,12 @@ class B(BaseModel): ) assert isinstance(m, A) assert m.foo_type == "a" - if PYDANTIC_V2: - assert m.data == 100 # type: ignore[comparison-overlap] - else: + if PYDANTIC_V1: # pydantic v1 automatically converts inputs to strings # if the expected type is a str assert m.data == "100" + else: + assert m.data == 100 # type: ignore[comparison-overlap] def test_discriminated_unions_overlapping_discriminators_invalid_data() -> None: @@ -833,7 +833,7 @@ class B(BaseModel): assert UnionType.__discriminator__ is discriminator -@pytest.mark.skipif(not PYDANTIC_V2, reason="TypeAliasType is not supported in Pydantic v1") +@pytest.mark.skipif(PYDANTIC_V1, reason="TypeAliasType is not supported in Pydantic v1") def test_type_alias_type() -> None: Alias = TypeAliasType("Alias", str) # pyright: ignore @@ -849,7 +849,7 @@ class Model(BaseModel): assert m.union == "bar" -@pytest.mark.skipif(not PYDANTIC_V2, reason="TypeAliasType is not supported in Pydantic v1") +@pytest.mark.skipif(PYDANTIC_V1, reason="TypeAliasType is not supported in Pydantic v1") def test_field_named_cls() -> None: class Model(BaseModel): cls: str @@ -936,7 +936,7 @@ class Type2(BaseModel): assert isinstance(model.value, InnerType2) -@pytest.mark.skipif(not PYDANTIC_V2, reason="this is only supported in pydantic v2 for now") +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2 for now") def test_extra_properties() -> None: class Item(BaseModel): prop: int diff --git a/tests/test_transform.py b/tests/test_transform.py index 69233f26..fe86aaaf 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -15,7 +15,7 @@ parse_datetime, async_transform as _async_transform, ) -from writerai._compat import PYDANTIC_V2 +from writerai._compat import PYDANTIC_V1 from writerai._models import BaseModel _T = TypeVar("_T") @@ -189,7 +189,7 @@ class DateModel(BaseModel): @pytest.mark.asyncio async def test_iso8601_format(use_async: bool) -> None: dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") - tz = "Z" if PYDANTIC_V2 else "+00:00" + tz = "+00:00" if PYDANTIC_V1 else "Z" assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692" + tz} # type: ignore[comparison-overlap] @@ -297,11 +297,11 @@ async def test_pydantic_unknown_field(use_async: bool) -> None: @pytest.mark.asyncio async def test_pydantic_mismatched_types(use_async: bool) -> None: model = MyModel.construct(foo=True) - if PYDANTIC_V2: + if PYDANTIC_V1: + params = await transform(model, Any, use_async) + else: with pytest.warns(UserWarning): params = await transform(model, Any, use_async) - else: - params = await transform(model, Any, use_async) assert cast(Any, params) == {"foo": True} @@ -309,11 +309,11 @@ async def test_pydantic_mismatched_types(use_async: bool) -> None: @pytest.mark.asyncio async def test_pydantic_mismatched_object_type(use_async: bool) -> None: model = MyModel.construct(foo=MyModel.construct(hello="world")) - if PYDANTIC_V2: + if PYDANTIC_V1: + params = await transform(model, Any, use_async) + else: with pytest.warns(UserWarning): params = await transform(model, Any, use_async) - else: - params = await transform(model, Any, use_async) assert cast(Any, params) == {"foo": {"hello": "world"}} diff --git a/tests/test_utils/test_datetime_parse.py b/tests/test_utils/test_datetime_parse.py new file mode 100644 index 00000000..ba09afb5 --- /dev/null +++ b/tests/test_utils/test_datetime_parse.py @@ -0,0 +1,110 @@ +""" +Copied from https://github.com/pydantic/pydantic/blob/v1.10.22/tests/test_datetime_parse.py +with modifications so it works without pydantic v1 imports. +""" + +from typing import Type, Union +from datetime import date, datetime, timezone, timedelta + +import pytest + +from writerai._utils import parse_date, parse_datetime + + +def create_tz(minutes: int) -> timezone: + return timezone(timedelta(minutes=minutes)) + + +@pytest.mark.parametrize( + "value,result", + [ + # Valid inputs + ("1494012444.883309", date(2017, 5, 5)), + (b"1494012444.883309", date(2017, 5, 5)), + (1_494_012_444.883_309, date(2017, 5, 5)), + ("1494012444", date(2017, 5, 5)), + (1_494_012_444, date(2017, 5, 5)), + (0, date(1970, 1, 1)), + ("2012-04-23", date(2012, 4, 23)), + (b"2012-04-23", date(2012, 4, 23)), + ("2012-4-9", date(2012, 4, 9)), + (date(2012, 4, 9), date(2012, 4, 9)), + (datetime(2012, 4, 9, 12, 15), date(2012, 4, 9)), + # Invalid inputs + ("x20120423", ValueError), + ("2012-04-56", ValueError), + (19_999_999_999, date(2603, 10, 11)), # just before watershed + (20_000_000_001, date(1970, 8, 20)), # just after watershed + (1_549_316_052, date(2019, 2, 4)), # nowish in s + (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms + (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs + (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns + ("infinity", date(9999, 12, 31)), + ("inf", date(9999, 12, 31)), + (float("inf"), date(9999, 12, 31)), + ("infinity ", date(9999, 12, 31)), + (int("1" + "0" * 100), date(9999, 12, 31)), + (1e1000, date(9999, 12, 31)), + ("-infinity", date(1, 1, 1)), + ("-inf", date(1, 1, 1)), + ("nan", ValueError), + ], +) +def test_date_parsing(value: Union[str, bytes, int, float], result: Union[date, Type[Exception]]) -> None: + if type(result) == type and issubclass(result, Exception): # pyright: ignore[reportUnnecessaryIsInstance] + with pytest.raises(result): + parse_date(value) + else: + assert parse_date(value) == result + + +@pytest.mark.parametrize( + "value,result", + [ + # Valid inputs + # values in seconds + ("1494012444.883309", datetime(2017, 5, 5, 19, 27, 24, 883_309, tzinfo=timezone.utc)), + (1_494_012_444.883_309, datetime(2017, 5, 5, 19, 27, 24, 883_309, tzinfo=timezone.utc)), + ("1494012444", datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + (b"1494012444", datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + (1_494_012_444, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + # values in ms + ("1494012444000.883309", datetime(2017, 5, 5, 19, 27, 24, 883, tzinfo=timezone.utc)), + ("-1494012444000.883309", datetime(1922, 8, 29, 4, 32, 35, 999117, tzinfo=timezone.utc)), + (1_494_012_444_000, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + ("2012-04-23T09:15:00", datetime(2012, 4, 23, 9, 15)), + ("2012-4-9 4:8:16", datetime(2012, 4, 9, 4, 8, 16)), + ("2012-04-23T09:15:00Z", datetime(2012, 4, 23, 9, 15, 0, 0, timezone.utc)), + ("2012-4-9 4:8:16-0320", datetime(2012, 4, 9, 4, 8, 16, 0, create_tz(-200))), + ("2012-04-23T10:20:30.400+02:30", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(150))), + ("2012-04-23T10:20:30.400+02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(120))), + ("2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))), + (b"2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))), + (datetime(2017, 5, 5), datetime(2017, 5, 5)), + (0, datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + # Invalid inputs + ("x20120423091500", ValueError), + ("2012-04-56T09:15:90", ValueError), + ("2012-04-23T11:05:00-25:00", ValueError), + (19_999_999_999, datetime(2603, 10, 11, 11, 33, 19, tzinfo=timezone.utc)), # just before watershed + (20_000_000_001, datetime(1970, 8, 20, 11, 33, 20, 1000, tzinfo=timezone.utc)), # just after watershed + (1_549_316_052, datetime(2019, 2, 4, 21, 34, 12, 0, tzinfo=timezone.utc)), # nowish in s + (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms + (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs + (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in ns + ("infinity", datetime(9999, 12, 31, 23, 59, 59, 999999)), + ("inf", datetime(9999, 12, 31, 23, 59, 59, 999999)), + ("inf ", datetime(9999, 12, 31, 23, 59, 59, 999999)), + (1e50, datetime(9999, 12, 31, 23, 59, 59, 999999)), + (float("inf"), datetime(9999, 12, 31, 23, 59, 59, 999999)), + ("-infinity", datetime(1, 1, 1, 0, 0)), + ("-inf", datetime(1, 1, 1, 0, 0)), + ("nan", ValueError), + ], +) +def test_datetime_parsing(value: Union[str, bytes, int, float], result: Union[datetime, Type[Exception]]) -> None: + if type(result) == type and issubclass(result, Exception): # pyright: ignore[reportUnnecessaryIsInstance] + with pytest.raises(result): + parse_datetime(value) + else: + assert parse_datetime(value) == result diff --git a/tests/utils.py b/tests/utils.py index b2f324aa..aa262bb7 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -22,7 +22,7 @@ is_annotated_type, is_type_alias_type, ) -from writerai._compat import PYDANTIC_V2, field_outer_type, get_model_fields +from writerai._compat import PYDANTIC_V1, field_outer_type, get_model_fields from writerai._models import BaseModel BaseModelT = TypeVar("BaseModelT", bound=BaseModel) @@ -31,12 +31,12 @@ def assert_matches_model(model: type[BaseModelT], value: BaseModelT, *, path: list[str]) -> bool: for name, field in get_model_fields(model).items(): field_value = getattr(value, name) - if PYDANTIC_V2: - allow_none = False - else: + if PYDANTIC_V1: # in v1 nullability was structured differently # https://docs.pydantic.dev/2.0/migration/#required-optional-and-nullable-fields allow_none = getattr(field, "allow_none", False) + else: + allow_none = False assert_matches_type( field_outer_type(field), From 251895049da0d7302cb37c599b0ca23dd0b6d470 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 4 Sep 2025 14:48:27 +0000 Subject: [PATCH 08/17] chore(internal): move mypy configurations to `pyproject.toml` file --- mypy.ini | 50 ------------------------------------------------ pyproject.toml | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 50 deletions(-) delete mode 100644 mypy.ini diff --git a/mypy.ini b/mypy.ini deleted file mode 100644 index 4a26acff..00000000 --- a/mypy.ini +++ /dev/null @@ -1,50 +0,0 @@ -[mypy] -pretty = True -show_error_codes = True - -# Exclude _files.py because mypy isn't smart enough to apply -# the correct type narrowing and as this is an internal module -# it's fine to just use Pyright. -# -# We also exclude our `tests` as mypy doesn't always infer -# types correctly and Pyright will still catch any type errors. -exclude = ^(src/writerai/_files\.py|_dev/.*\.py|tests/.*)$ - -strict_equality = True -implicit_reexport = True -check_untyped_defs = True -no_implicit_optional = True - -warn_return_any = True -warn_unreachable = True -warn_unused_configs = True - -# Turn these options off as it could cause conflicts -# with the Pyright options. -warn_unused_ignores = False -warn_redundant_casts = False - -disallow_any_generics = True -disallow_untyped_defs = True -disallow_untyped_calls = True -disallow_subclassing_any = True -disallow_incomplete_defs = True -disallow_untyped_decorators = True -cache_fine_grained = True - -# By default, mypy reports an error if you assign a value to the result -# of a function call that doesn't return anything. We do this in our test -# cases: -# ``` -# result = ... -# assert result is None -# ``` -# Changing this codegen to make mypy happy would increase complexity -# and would not be worth it. -disable_error_code = func-returns-value,overload-cannot-match - -# https://github.com/python/mypy/issues/12162 -[mypy.overrides] -module = "black.files.*" -ignore_errors = true -ignore_missing_imports = true diff --git a/pyproject.toml b/pyproject.toml index 2278b83a..34ede76d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -160,6 +160,58 @@ reportOverlappingOverload = false reportImportCycles = false reportPrivateUsage = false +[tool.mypy] +pretty = true +show_error_codes = true + +# Exclude _files.py because mypy isn't smart enough to apply +# the correct type narrowing and as this is an internal module +# it's fine to just use Pyright. +# +# We also exclude our `tests` as mypy doesn't always infer +# types correctly and Pyright will still catch any type errors. +exclude = ['src/writerai/_files.py', '_dev/.*.py', 'tests/.*'] + +strict_equality = true +implicit_reexport = true +check_untyped_defs = true +no_implicit_optional = true + +warn_return_any = true +warn_unreachable = true +warn_unused_configs = true + +# Turn these options off as it could cause conflicts +# with the Pyright options. +warn_unused_ignores = false +warn_redundant_casts = false + +disallow_any_generics = true +disallow_untyped_defs = true +disallow_untyped_calls = true +disallow_subclassing_any = true +disallow_incomplete_defs = true +disallow_untyped_decorators = true +cache_fine_grained = true + +# By default, mypy reports an error if you assign a value to the result +# of a function call that doesn't return anything. We do this in our test +# cases: +# ``` +# result = ... +# assert result is None +# ``` +# Changing this codegen to make mypy happy would increase complexity +# and would not be worth it. +disable_error_code = "func-returns-value,overload-cannot-match" + +# https://github.com/python/mypy/issues/12162 +[[tool.mypy.overrides]] +module = "black.files.*" +ignore_errors = true +ignore_missing_imports = true + + [tool.ruff] line-length = 120 output-format = "grouped" From 5f8a109801baff44a41313e2a4774ecc2c7e70bd Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 4 Sep 2025 22:00:18 +0000 Subject: [PATCH 09/17] docs(api): updates to API spec --- .stats.yml | 4 ++-- src/writerai/types/application_list_response.py | 3 +++ src/writerai/types/application_retrieve_response.py | 3 +++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index cf180159..9ef1b2b5 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 33 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/writerai%2Fwriter-9e04c6a51c55704029c529f2917d0e2b976cb7b6595128697db031ad7bd61a63.yml -openapi_spec_hash: e8a95522dd13ffe4633cccc34bbd651d +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/writerai%2Fwriter-321826aa393f6f2c2e2ccc8b20795157f8b55908a96b4c28d90272f306ee3ff4.yml +openapi_spec_hash: ccf23a9557962bab6ed52a94a25ecf1c config_hash: 7a38bab086b53b43d2a719cb4d883264 diff --git a/src/writerai/types/application_list_response.py b/src/writerai/types/application_list_response.py index 7f8e9fb0..e80b6e90 100644 --- a/src/writerai/types/application_list_response.py +++ b/src/writerai/types/application_list_response.py @@ -35,6 +35,9 @@ class InputOptionsApplicationInputFileOptions(BaseModel): max_word_count: int """Maximum number of words allowed in text files.""" + upload_types: List[Literal["url", "file_id"]] + """List of allowed upload types for file inputs.""" + class InputOptionsApplicationInputMediaOptions(BaseModel): file_types: List[str] diff --git a/src/writerai/types/application_retrieve_response.py b/src/writerai/types/application_retrieve_response.py index c195b145..00827b7a 100644 --- a/src/writerai/types/application_retrieve_response.py +++ b/src/writerai/types/application_retrieve_response.py @@ -35,6 +35,9 @@ class InputOptionsApplicationInputFileOptions(BaseModel): max_word_count: int """Maximum number of words allowed in text files.""" + upload_types: List[Literal["url", "file_id"]] + """List of allowed upload types for file inputs.""" + class InputOptionsApplicationInputMediaOptions(BaseModel): file_types: List[str] From 8a26e46ec365ea9905be7531bd80ebd9c74b129d Mon Sep 17 00:00:00 2001 From: David Meadows Date: Thu, 11 Sep 2025 16:51:30 -0400 Subject: [PATCH 10/17] fix(client): custom patch to prepare pydantic v3 --- requirements-dev.lock | 8 ++++---- requirements.lock | 4 ++-- src/writerai/_compat.py | 12 ++++++------ src/writerai/lib/_parsing/_completions.py | 6 +++--- src/writerai/lib/_pydantic.py | 6 +++--- src/writerai/resources/chat.py | 2 +- 6 files changed, 19 insertions(+), 19 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 1285d614..7c31b2f7 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -24,12 +24,12 @@ anyio==4.4.0 # via writer-sdk argcomplete==3.1.2 # via nox +asttokens==3.0.0 + # via inline-snapshot async-timeout==5.0.1 # via aiohttp attrs==25.3.0 # via aiohttp -asttokens==3.0.0 - # via inline-snapshot certifi==2023.7.22 # via httpcore # via httpx @@ -43,10 +43,10 @@ distro==1.8.0 exceptiongroup==1.2.2 # via anyio # via pytest -executing==2.2.0 - # via inline-snapshot execnet==2.1.1 # via pytest-xdist +executing==2.2.0 + # via inline-snapshot filelock==3.12.4 # via virtualenv frozenlist==1.6.2 diff --git a/requirements.lock b/requirements.lock index 85b74322..87f0c543 100644 --- a/requirements.lock +++ b/requirements.lock @@ -49,14 +49,14 @@ idna==3.4 # via anyio # via httpx # via yarl +jiter==0.8.2 + # via writer-sdk multidict==6.4.4 # via aiohttp # via yarl propcache==0.3.1 # via aiohttp # via yarl -jiter==0.8.2 - # via writer-sdk pydantic==2.10.3 # via writer-sdk pydantic-core==2.27.1 diff --git a/src/writerai/_compat.py b/src/writerai/_compat.py index 7d15e6b3..73a1f3ea 100644 --- a/src/writerai/_compat.py +++ b/src/writerai/_compat.py @@ -166,15 +166,15 @@ def model_parse(model: type[_ModelT], data: Any) -> _ModelT: def model_parse_json(model: type[_ModelT], data: str | bytes) -> _ModelT: - if PYDANTIC_V2: - return model.model_validate_json(data) - return model.parse_raw(data) # pyright: ignore[reportDeprecated] + if PYDANTIC_V1: + return model.parse_raw(data) # pyright: ignore[reportDeprecated] + return model.model_validate_json(data) def model_json_schema(model: type[_ModelT]) -> dict[str, Any]: - if PYDANTIC_V2: - return model.model_json_schema() - return model.schema() # pyright: ignore[reportDeprecated] + if PYDANTIC_V1: + return model.schema() # pyright: ignore[reportDeprecated] + return model.model_json_schema() # generic models diff --git a/src/writerai/lib/_parsing/_completions.py b/src/writerai/lib/_parsing/_completions.py index 9d01c816..6788f4b0 100644 --- a/src/writerai/lib/_parsing/_completions.py +++ b/src/writerai/lib/_parsing/_completions.py @@ -9,7 +9,7 @@ from .._tools import PydanticFunctionTool from ..._types import NOT_GIVEN, NotGiven from ..._utils import is_dict, is_given -from ..._compat import PYDANTIC_V2, model_parse_json +from ..._compat import PYDANTIC_V1, model_parse_json from ..._models import construct_type_unchecked from .._pydantic import is_basemodel_type, to_strict_json_schema, is_dataclass_like_type from ..._exceptions import LengthFinishReasonError, ContentFilterFinishReasonError @@ -220,8 +220,8 @@ def _parse_content(response_format: type[ResponseFormatT], content: str) -> Resp return cast(ResponseFormatT, model_parse_json(response_format, content)) if is_dataclass_like_type(response_format): - if not PYDANTIC_V2: - raise TypeError(f"Non BaseModel types are only supported with Pydantic v2 - {response_format}") + if PYDANTIC_V1: + raise TypeError(f"Non BaseModel types not supported with Pydantic v1 - {response_format}") return pydantic.TypeAdapter(response_format).validate_json(content) diff --git a/src/writerai/lib/_pydantic.py b/src/writerai/lib/_pydantic.py index 22c7a1f3..d7fb8834 100644 --- a/src/writerai/lib/_pydantic.py +++ b/src/writerai/lib/_pydantic.py @@ -8,7 +8,7 @@ from .._types import NOT_GIVEN from .._utils import is_dict as _is_dict, is_list -from .._compat import PYDANTIC_V2, model_json_schema +from .._compat import PYDANTIC_V1, model_json_schema _T = TypeVar("_T") @@ -16,10 +16,10 @@ def to_strict_json_schema(model: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any]) -> dict[str, Any]: if inspect.isclass(model) and is_basemodel_type(model): schema = model_json_schema(model) - elif PYDANTIC_V2 and isinstance(model, pydantic.TypeAdapter): + elif not PYDANTIC_V1 and isinstance(model, pydantic.TypeAdapter): schema = model.json_schema() else: - raise TypeError(f"Non BaseModel types are only supported with Pydantic v2 - {model}") + raise TypeError(f"Non BaseModel types are not supported with Pydantic v1 - {model}") return _ensure_strict_json_schema(schema, path=(), root=schema) diff --git a/src/writerai/resources/chat.py b/src/writerai/resources/chat.py index dd18cf45..2a8b8d28 100644 --- a/src/writerai/resources/chat.py +++ b/src/writerai/resources/chat.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Type, Union, TypeVar, Iterable +from typing import List, Type, Union, TypeVar, Iterable from functools import partial from typing_extensions import Literal, overload From f1ddbb236dbc6c1780eb1120e2fba20c0e4c921a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 11 Sep 2025 21:34:44 +0000 Subject: [PATCH 11/17] chore(tests): simplify `get_platform` test `nest_asyncio` is archived and broken on some platforms so it's not worth keeping in our test suite. --- tests/test_client.py | 53 +++++--------------------------------------- 1 file changed, 6 insertions(+), 47 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 03dbad51..c8a764ce 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -6,13 +6,10 @@ import os import sys import json -import time import asyncio import inspect -import subprocess import tracemalloc from typing import Any, Union, cast -from textwrap import dedent from unittest import mock from typing_extensions import Literal @@ -23,6 +20,7 @@ from writerai import Writer, AsyncWriter, APIResponseValidationError from writerai._types import Omit +from writerai._utils import asyncify from writerai._models import BaseModel, FinalRequestOptions from writerai._streaming import Stream, AsyncStream from writerai._exceptions import WriterError, APIStatusError, APITimeoutError, APIResponseValidationError @@ -30,8 +28,10 @@ DEFAULT_TIMEOUT, HTTPX_DEFAULT_TIMEOUT, BaseClient, + OtherPlatform, DefaultHttpxClient, DefaultAsyncHttpxClient, + get_platform, make_request_options, ) @@ -1659,50 +1659,9 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: assert response.http_request.headers.get("x-stainless-retry-count") == "42" - def test_get_platform(self) -> None: - # A previous implementation of asyncify could leave threads unterminated when - # used with nest_asyncio. - # - # Since nest_asyncio.apply() is global and cannot be un-applied, this - # test is run in a separate process to avoid affecting other tests. - test_code = dedent(""" - import asyncio - import nest_asyncio - import threading - - from writerai._utils import asyncify - from writerai._base_client import get_platform - - async def test_main() -> None: - result = await asyncify(get_platform)() - print(result) - for thread in threading.enumerate(): - print(thread.name) - - nest_asyncio.apply() - asyncio.run(test_main()) - """) - with subprocess.Popen( - [sys.executable, "-c", test_code], - text=True, - ) as process: - timeout = 10 # seconds - - start_time = time.monotonic() - while True: - return_code = process.poll() - if return_code is not None: - if return_code != 0: - raise AssertionError("calling get_platform using asyncify resulted in a non-zero exit code") - - # success - break - - if time.monotonic() - start_time > timeout: - process.kill() - raise AssertionError("calling get_platform using asyncify resulted in a hung process") - - time.sleep(0.1) + async def test_get_platform(self) -> None: + platform = await asyncify(get_platform)() + assert isinstance(platform, (str, OtherPlatform)) async def test_proxy_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None: # Test that the proxy environment variables are set correctly From d78241fcd031546a40c9227b2362e7af2c28bd8c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 10 Sep 2025 18:47:14 +0000 Subject: [PATCH 12/17] codegen metadata --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 9ef1b2b5..ca6b61b9 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 33 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/writerai%2Fwriter-321826aa393f6f2c2e2ccc8b20795157f8b55908a96b4c28d90272f306ee3ff4.yml openapi_spec_hash: ccf23a9557962bab6ed52a94a25ecf1c -config_hash: 7a38bab086b53b43d2a719cb4d883264 +config_hash: d655a846f6872554a75412b27b6ed71f From 1a8c6dcd013b502f2247462a9071c4fefaf45a94 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 11 Sep 2025 20:01:01 +0000 Subject: [PATCH 13/17] codegen metadata --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index ca6b61b9..9ef1b2b5 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 33 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/writerai%2Fwriter-321826aa393f6f2c2e2ccc8b20795157f8b55908a96b4c28d90272f306ee3ff4.yml openapi_spec_hash: ccf23a9557962bab6ed52a94a25ecf1c -config_hash: d655a846f6872554a75412b27b6ed71f +config_hash: 7a38bab086b53b43d2a719cb4d883264 From daf31d587a7bc32c9debe961ac870d08fedef865 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 11 Sep 2025 20:35:18 +0000 Subject: [PATCH 14/17] docs(api): updates to API spec --- .stats.yml | 4 +- src/writerai/resources/graphs.py | 28 +++++++ src/writerai/types/graph_question_params.py | 75 ++++++++++++++++++- src/writerai/types/question.py | 69 ++++++++++++++++- src/writerai/types/shared/graph_data.py | 5 +- src/writerai/types/shared/source.py | 7 +- src/writerai/types/shared/tool_param.py | 74 ++++++++++++++++++ .../types/shared_params/graph_data.py | 5 +- src/writerai/types/shared_params/source.py | 7 +- .../types/shared_params/tool_param.py | 74 ++++++++++++++++++ tests/api_resources/test_graphs.py | 40 ++++++++++ 11 files changed, 374 insertions(+), 14 deletions(-) diff --git a/.stats.yml b/.stats.yml index 9ef1b2b5..1822dc87 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 33 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/writerai%2Fwriter-321826aa393f6f2c2e2ccc8b20795157f8b55908a96b4c28d90272f306ee3ff4.yml -openapi_spec_hash: ccf23a9557962bab6ed52a94a25ecf1c +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/writerai%2Fwriter-3f87c8deb39e443022f2e04252994a6c9d25473872503edf9eec00d874576b2d.yml +openapi_spec_hash: 5de52bf1d78e00b13a04f6e9ce2f2fb5 config_hash: 7a38bab086b53b43d2a719cb4d883264 diff --git a/src/writerai/resources/graphs.py b/src/writerai/resources/graphs.py index 85988d5d..ebb822c8 100644 --- a/src/writerai/resources/graphs.py +++ b/src/writerai/resources/graphs.py @@ -360,6 +360,7 @@ def question( *, graph_ids: SequenceNotStr[str], question: str, + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, stream: Literal[False] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -377,6 +378,9 @@ def question( question: The question to answer using the Knowledge Graph. + query_config: Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + stream: Determines whether the model's output should be streamed. If true, the output is generated and sent incrementally, which can be useful for real-time applications. @@ -400,6 +404,7 @@ def question( graph_ids: SequenceNotStr[str], question: str, stream: Literal[True], + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -420,6 +425,9 @@ def question( generated and sent incrementally, which can be useful for real-time applications. + query_config: Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + subqueries: Specify whether to include subqueries. extra_headers: Send extra headers @@ -439,6 +447,7 @@ def question( graph_ids: SequenceNotStr[str], question: str, stream: bool, + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -459,6 +468,9 @@ def question( generated and sent incrementally, which can be useful for real-time applications. + query_config: Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + subqueries: Specify whether to include subqueries. extra_headers: Send extra headers @@ -477,6 +489,7 @@ def question( *, graph_ids: SequenceNotStr[str], question: str, + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -492,6 +505,7 @@ def question( { "graph_ids": graph_ids, "question": question, + "query_config": query_config, "stream": stream, "subqueries": subqueries, }, @@ -867,6 +881,7 @@ async def question( *, graph_ids: SequenceNotStr[str], question: str, + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, stream: Literal[False] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -884,6 +899,9 @@ async def question( question: The question to answer using the Knowledge Graph. + query_config: Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + stream: Determines whether the model's output should be streamed. If true, the output is generated and sent incrementally, which can be useful for real-time applications. @@ -907,6 +925,7 @@ async def question( graph_ids: SequenceNotStr[str], question: str, stream: Literal[True], + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -927,6 +946,9 @@ async def question( generated and sent incrementally, which can be useful for real-time applications. + query_config: Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + subqueries: Specify whether to include subqueries. extra_headers: Send extra headers @@ -946,6 +968,7 @@ async def question( graph_ids: SequenceNotStr[str], question: str, stream: bool, + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -966,6 +989,9 @@ async def question( generated and sent incrementally, which can be useful for real-time applications. + query_config: Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + subqueries: Specify whether to include subqueries. extra_headers: Send extra headers @@ -984,6 +1010,7 @@ async def question( *, graph_ids: SequenceNotStr[str], question: str, + query_config: graph_question_params.QueryConfig | NotGiven = NOT_GIVEN, stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, subqueries: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -999,6 +1026,7 @@ async def question( { "graph_ids": graph_ids, "question": question, + "query_config": query_config, "stream": stream, "subqueries": subqueries, }, diff --git a/src/writerai/types/graph_question_params.py b/src/writerai/types/graph_question_params.py index 02e8b513..a49563c7 100644 --- a/src/writerai/types/graph_question_params.py +++ b/src/writerai/types/graph_question_params.py @@ -7,7 +7,7 @@ from .._types import SequenceNotStr -__all__ = ["GraphQuestionParamsBase", "GraphQuestionParamsNonStreaming", "GraphQuestionParamsStreaming"] +__all__ = ["GraphQuestionParamsBase", "QueryConfig", "GraphQuestionParamsNonStreaming", "GraphQuestionParamsStreaming"] class GraphQuestionParamsBase(TypedDict, total=False): @@ -17,10 +17,83 @@ class GraphQuestionParamsBase(TypedDict, total=False): question: Required[str] """The question to answer using the Knowledge Graph.""" + query_config: QueryConfig + """ + Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + """ + subqueries: bool """Specify whether to include subqueries.""" +class QueryConfig(TypedDict, total=False): + grounding_level: float + """ + Level of grounding required for responses, controlling how closely answers must + be tied to source material. Set lower for grounded outputs, higher for + creativity. Higher values (closer to 1.0) allow more creative interpretation, + while lower values (closer to 0.0) stick more closely to source material. Range: + 0.0-1.0, Default: 0.0. + """ + + inline_citations: bool + """ + Whether to include inline citations in the response, showing which Knowledge + Graph sources were used. Default: false. + """ + + keyword_threshold: float + """Threshold for keyword-based matching when searching Knowledge Graph content. + + Set higher for stricter relevance, lower for broader range. Higher values + (closer to 1.0) require stronger keyword matches, while lower values (closer to + 0.0) allow more lenient matching. Range: 0.0-1.0, Default: 0.7. + """ + + max_snippets: int + """Maximum number of text snippets to retrieve from the Knowledge Graph for + context. + + Works in concert with `search_weight` to control best matches vs broader + coverage. While technically supports 1-60, values below 5 may return no results + due to RAG implementation. Recommended range: 5-25. Due to RAG system behavior, + you may see more snippets than requested. Range: 1-60, Default: 30. + """ + + max_subquestions: int + """Maximum number of subquestions to generate when processing complex queries. + + Set higher to improve detail, set lower to reduce response time. Range: 1-10, + Default: 6. + """ + + max_tokens: int + """Maximum number of tokens the model can generate in the response. + + This controls the length of the AI's answer. Set higher for longer answers, set + lower for shorter, faster answers. Range: 100-8000, Default: 4000. + """ + + search_weight: int + """Weight given to search results when ranking and selecting relevant information. + + Higher values (closer to 100) prioritize keyword-based matching, while lower + values (closer to 0) prioritize semantic similarity matching. Use higher values + for exact keyword searches, lower values for conceptual similarity searches. + Range: 0-100, Default: 50. + """ + + semantic_threshold: float + """ + Threshold for semantic similarity matching when searching Knowledge Graph + content. Set higher for stricter relevance, lower for broader range. Higher + values (closer to 1.0) require stronger semantic similarity, while lower values + (closer to 0.0) allow more lenient semantic matching. Range: 0.0-1.0, Default: + 0.7. + """ + + class GraphQuestionParamsNonStreaming(GraphQuestionParamsBase, total=False): stream: Literal[False] """Determines whether the model's output should be streamed. diff --git a/src/writerai/types/question.py b/src/writerai/types/question.py index 4d4d8871..9f3095bb 100644 --- a/src/writerai/types/question.py +++ b/src/writerai/types/question.py @@ -2,20 +2,77 @@ from typing import List, Optional +from pydantic import Field as FieldInfo + from .._models import BaseModel from .shared.source import Source -__all__ = ["Question", "Subquery"] +__all__ = ["Question", "References", "ReferencesFile", "ReferencesWeb", "Subquery"] + + +class ReferencesFile(BaseModel): + file_id: str = FieldInfo(alias="fileId") + """The unique identifier of the file in your Writer account.""" + + score: float + """ + Internal score used during the retrieval process for ranking and selecting + relevant snippets. + """ + + text: str + """ + The exact text snippet from the source document that was used to support the + response. + """ + + cite: Optional[str] = None + """ + Unique citation ID that appears in inline citations within the response text + (null if not cited). + """ + + page: Optional[int] = None + """Page number where this snippet was found in the source document.""" + + +class ReferencesWeb(BaseModel): + score: float + """ + Internal score used during the retrieval process for ranking and selecting + relevant snippets. + """ + + text: str + """ + The exact text snippet from the web source that was used to support the + response. + """ + + title: str + """The title of the web page where this content was found.""" + + url: str + """The URL of the web page where this content was found.""" + + +class References(BaseModel): + files: Optional[List[ReferencesFile]] = None + """Array of file-based references from uploaded documents in the Knowledge Graph.""" + + web: Optional[List[ReferencesWeb]] = None + """Array of web-based references from online sources accessed during the query.""" class Subquery(BaseModel): answer: str - """The answer to the subquery.""" + """The answer to the subquery based on Knowledge Graph content.""" query: str - """The subquery that was asked.""" + """The subquery that was generated to help answer the main question.""" sources: List[Optional[Source]] + """Array of source snippets that were used to answer this subquery.""" class Question(BaseModel): @@ -27,4 +84,10 @@ class Question(BaseModel): sources: List[Optional[Source]] + references: Optional[References] = None + """ + Detailed source information organized by reference type, providing comprehensive + metadata about the sources used to generate the response. + """ + subqueries: Optional[List[Optional[Subquery]]] = None diff --git a/src/writerai/types/shared/graph_data.py b/src/writerai/types/shared/graph_data.py index ad78cf72..6898bddd 100644 --- a/src/writerai/types/shared/graph_data.py +++ b/src/writerai/types/shared/graph_data.py @@ -11,12 +11,13 @@ class Subquery(BaseModel): answer: str - """The answer to the subquery.""" + """The answer to the subquery based on Knowledge Graph content.""" query: str - """The subquery that was asked.""" + """The subquery that was generated to help answer the main question.""" sources: List[Optional[Source]] + """Array of source snippets that were used to answer this subquery.""" class GraphData(BaseModel): diff --git a/src/writerai/types/shared/source.py b/src/writerai/types/shared/source.py index 36ae2008..326d01ad 100644 --- a/src/writerai/types/shared/source.py +++ b/src/writerai/types/shared/source.py @@ -7,7 +7,10 @@ class Source(BaseModel): file_id: str - """The unique identifier of the file.""" + """The unique identifier of the file in your Writer account.""" snippet: str - """A snippet of text from the source file.""" + """ + The exact text snippet from the source document that was used to support the + response. + """ diff --git a/src/writerai/types/shared/tool_param.py b/src/writerai/types/shared/tool_param.py index f5186ef1..c88d8aec 100644 --- a/src/writerai/types/shared/tool_param.py +++ b/src/writerai/types/shared/tool_param.py @@ -12,6 +12,7 @@ "FunctionTool", "GraphTool", "GraphToolFunction", + "GraphToolFunctionQueryConfig", "LlmTool", "LlmToolFunction", "TranslationTool", @@ -32,6 +33,73 @@ class FunctionTool(BaseModel): """The type of tool.""" +class GraphToolFunctionQueryConfig(BaseModel): + grounding_level: Optional[float] = None + """ + Level of grounding required for responses, controlling how closely answers must + be tied to source material. Set lower for grounded outputs, higher for + creativity. Higher values (closer to 1.0) allow more creative interpretation, + while lower values (closer to 0.0) stick more closely to source material. Range: + 0.0-1.0, Default: 0.0. + """ + + inline_citations: Optional[bool] = None + """ + Whether to include inline citations in the response, showing which Knowledge + Graph sources were used. Default: false. + """ + + keyword_threshold: Optional[float] = None + """Threshold for keyword-based matching when searching Knowledge Graph content. + + Set higher for stricter relevance, lower for broader range. Higher values + (closer to 1.0) require stronger keyword matches, while lower values (closer to + 0.0) allow more lenient matching. Range: 0.0-1.0, Default: 0.7. + """ + + max_snippets: Optional[int] = None + """Maximum number of text snippets to retrieve from the Knowledge Graph for + context. + + Works in concert with `search_weight` to control best matches vs broader + coverage. While technically supports 1-60, values below 5 may return no results + due to RAG implementation. Recommended range: 5-25. Due to RAG system behavior, + you may see more snippets than requested. Range: 1-60, Default: 30. + """ + + max_subquestions: Optional[int] = None + """Maximum number of subquestions to generate when processing complex queries. + + Set higher to improve detail, set lower to reduce response time. Range: 1-10, + Default: 6. + """ + + max_tokens: Optional[int] = None + """Maximum number of tokens the model can generate in the response. + + This controls the length of the AI's answer. Set higher for longer answers, set + lower for shorter, faster answers. Range: 100-8000, Default: 4000. + """ + + search_weight: Optional[int] = None + """Weight given to search results when ranking and selecting relevant information. + + Higher values (closer to 100) prioritize keyword-based matching, while lower + values (closer to 0) prioritize semantic similarity matching. Use higher values + for exact keyword searches, lower values for conceptual similarity searches. + Range: 0-100, Default: 50. + """ + + semantic_threshold: Optional[float] = None + """ + Threshold for semantic similarity matching when searching Knowledge Graph + content. Set higher for stricter relevance, lower for broader range. Higher + values (closer to 1.0) require stronger semantic similarity, while lower values + (closer to 0.0) allow more lenient semantic matching. Range: 0.0-1.0, Default: + 0.7. + """ + + class GraphToolFunction(BaseModel): graph_ids: List[str] """An array of graph IDs to use in the tool.""" @@ -42,6 +110,12 @@ class GraphToolFunction(BaseModel): description: Optional[str] = None """A description of the graph content.""" + query_config: Optional[GraphToolFunctionQueryConfig] = None + """ + Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + """ + class GraphTool(BaseModel): function: GraphToolFunction diff --git a/src/writerai/types/shared_params/graph_data.py b/src/writerai/types/shared_params/graph_data.py index 39ede602..caa1e6d5 100644 --- a/src/writerai/types/shared_params/graph_data.py +++ b/src/writerai/types/shared_params/graph_data.py @@ -12,12 +12,13 @@ class Subquery(TypedDict, total=False): answer: Required[str] - """The answer to the subquery.""" + """The answer to the subquery based on Knowledge Graph content.""" query: Required[str] - """The subquery that was asked.""" + """The subquery that was generated to help answer the main question.""" sources: Required[Iterable[Optional[Source]]] + """Array of source snippets that were used to answer this subquery.""" class GraphData(TypedDict, total=False): diff --git a/src/writerai/types/shared_params/source.py b/src/writerai/types/shared_params/source.py index 54b70059..dc6726ba 100644 --- a/src/writerai/types/shared_params/source.py +++ b/src/writerai/types/shared_params/source.py @@ -9,7 +9,10 @@ class Source(TypedDict, total=False): file_id: Required[str] - """The unique identifier of the file.""" + """The unique identifier of the file in your Writer account.""" snippet: Required[str] - """A snippet of text from the source file.""" + """ + The exact text snippet from the source document that was used to support the + response. + """ diff --git a/src/writerai/types/shared_params/tool_param.py b/src/writerai/types/shared_params/tool_param.py index 677a33bd..c881bcb5 100644 --- a/src/writerai/types/shared_params/tool_param.py +++ b/src/writerai/types/shared_params/tool_param.py @@ -13,6 +13,7 @@ "FunctionTool", "GraphTool", "GraphToolFunction", + "GraphToolFunctionQueryConfig", "LlmTool", "LlmToolFunction", "TranslationTool", @@ -33,6 +34,73 @@ class FunctionTool(TypedDict, total=False): """The type of tool.""" +class GraphToolFunctionQueryConfig(TypedDict, total=False): + grounding_level: float + """ + Level of grounding required for responses, controlling how closely answers must + be tied to source material. Set lower for grounded outputs, higher for + creativity. Higher values (closer to 1.0) allow more creative interpretation, + while lower values (closer to 0.0) stick more closely to source material. Range: + 0.0-1.0, Default: 0.0. + """ + + inline_citations: bool + """ + Whether to include inline citations in the response, showing which Knowledge + Graph sources were used. Default: false. + """ + + keyword_threshold: float + """Threshold for keyword-based matching when searching Knowledge Graph content. + + Set higher for stricter relevance, lower for broader range. Higher values + (closer to 1.0) require stronger keyword matches, while lower values (closer to + 0.0) allow more lenient matching. Range: 0.0-1.0, Default: 0.7. + """ + + max_snippets: int + """Maximum number of text snippets to retrieve from the Knowledge Graph for + context. + + Works in concert with `search_weight` to control best matches vs broader + coverage. While technically supports 1-60, values below 5 may return no results + due to RAG implementation. Recommended range: 5-25. Due to RAG system behavior, + you may see more snippets than requested. Range: 1-60, Default: 30. + """ + + max_subquestions: int + """Maximum number of subquestions to generate when processing complex queries. + + Set higher to improve detail, set lower to reduce response time. Range: 1-10, + Default: 6. + """ + + max_tokens: int + """Maximum number of tokens the model can generate in the response. + + This controls the length of the AI's answer. Set higher for longer answers, set + lower for shorter, faster answers. Range: 100-8000, Default: 4000. + """ + + search_weight: int + """Weight given to search results when ranking and selecting relevant information. + + Higher values (closer to 100) prioritize keyword-based matching, while lower + values (closer to 0) prioritize semantic similarity matching. Use higher values + for exact keyword searches, lower values for conceptual similarity searches. + Range: 0-100, Default: 50. + """ + + semantic_threshold: float + """ + Threshold for semantic similarity matching when searching Knowledge Graph + content. Set higher for stricter relevance, lower for broader range. Higher + values (closer to 1.0) require stronger semantic similarity, while lower values + (closer to 0.0) allow more lenient semantic matching. Range: 0.0-1.0, Default: + 0.7. + """ + + class GraphToolFunction(TypedDict, total=False): graph_ids: Required[SequenceNotStr[str]] """An array of graph IDs to use in the tool.""" @@ -43,6 +111,12 @@ class GraphToolFunction(TypedDict, total=False): description: str """A description of the graph content.""" + query_config: GraphToolFunctionQueryConfig + """ + Configuration options for Knowledge Graph queries, including search parameters + and citation settings. + """ + class GraphTool(TypedDict, total=False): function: Required[GraphToolFunction] diff --git a/tests/api_resources/test_graphs.py b/tests/api_resources/test_graphs.py index 005c9cab..d4859225 100644 --- a/tests/api_resources/test_graphs.py +++ b/tests/api_resources/test_graphs.py @@ -279,6 +279,16 @@ def test_method_question_with_all_params_overload_1(self, client: Writer) -> Non graph = client.graphs.question( graph_ids=["182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e"], question="question", + query_config={ + "grounding_level": 0, + "inline_citations": True, + "keyword_threshold": 0, + "max_snippets": 1, + "max_subquestions": 1, + "max_tokens": 100, + "search_weight": 0, + "semantic_threshold": 0, + }, stream=False, subqueries=True, ) @@ -325,6 +335,16 @@ def test_method_question_with_all_params_overload_2(self, client: Writer) -> Non graph_ids=["182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e"], question="question", stream=True, + query_config={ + "grounding_level": 0, + "inline_citations": True, + "keyword_threshold": 0, + "max_snippets": 1, + "max_subquestions": 1, + "max_tokens": 100, + "search_weight": 0, + "semantic_threshold": 0, + }, subqueries=True, ) graph_stream.response.close() @@ -663,6 +683,16 @@ async def test_method_question_with_all_params_overload_1(self, async_client: As graph = await async_client.graphs.question( graph_ids=["182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e"], question="question", + query_config={ + "grounding_level": 0, + "inline_citations": True, + "keyword_threshold": 0, + "max_snippets": 1, + "max_subquestions": 1, + "max_tokens": 100, + "search_weight": 0, + "semantic_threshold": 0, + }, stream=False, subqueries=True, ) @@ -709,6 +739,16 @@ async def test_method_question_with_all_params_overload_2(self, async_client: As graph_ids=["182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e"], question="question", stream=True, + query_config={ + "grounding_level": 0, + "inline_citations": True, + "keyword_threshold": 0, + "max_snippets": 1, + "max_subquestions": 1, + "max_tokens": 100, + "search_weight": 0, + "semantic_threshold": 0, + }, subqueries=True, ) await graph_stream.response.aclose() From 8920408285a5adfe7d0a416bc4539e42326b180e Mon Sep 17 00:00:00 2001 From: David Meadows Date: Thu, 11 Sep 2025 17:37:52 -0400 Subject: [PATCH 15/17] chore(client): update stop params in stream/parse to match chat --- src/writerai/resources/chat.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/writerai/resources/chat.py b/src/writerai/resources/chat.py index 2a8b8d28..f5195293 100644 --- a/src/writerai/resources/chat.py +++ b/src/writerai/resources/chat.py @@ -440,7 +440,7 @@ def parse( logprobs: bool | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, @@ -549,7 +549,7 @@ def stream( logprobs: bool | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, @@ -1014,7 +1014,7 @@ async def parse( logprobs: bool | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, @@ -1123,7 +1123,7 @@ def stream( logprobs: bool | NotGiven = NOT_GIVEN, max_tokens: int | NotGiven = NOT_GIVEN, n: int | NotGiven = NOT_GIVEN, - stop: Union[List[str], str] | NotGiven = NOT_GIVEN, + stop: Union[SequenceNotStr[str], str] | NotGiven = NOT_GIVEN, stream_options: chat_chat_params.StreamOptions | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: chat_chat_params.ToolChoice | NotGiven = NOT_GIVEN, From fa024a58b0bc88104744f17279f5ca3819f28284 Mon Sep 17 00:00:00 2001 From: David Meadows Date: Thu, 11 Sep 2025 17:39:04 -0400 Subject: [PATCH 16/17] chore(client): format --- src/writerai/_client.py | 7 ++----- src/writerai/resources/chat.py | 2 +- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/writerai/_client.py b/src/writerai/_client.py index 1f0e5c88..0f9ef3b7 100644 --- a/src/writerai/_client.py +++ b/src/writerai/_client.py @@ -58,12 +58,9 @@ def _extract_sdk_env_headers() -> dict[str, str]: continue # Strip the prefix and convert - raw = key[len(_SDK_HEADER_PREFIX):] + raw = key[len(_SDK_HEADER_PREFIX) :] parts = raw.split("_") - canonical = "-".join( - word.capitalize() if len(word) > 1 else word.upper() - for word in parts - ) + canonical = "-".join(word.capitalize() if len(word) > 1 else word.upper() for word in parts) headers[canonical] = value return headers diff --git a/src/writerai/resources/chat.py b/src/writerai/resources/chat.py index f5195293..e178aa7f 100644 --- a/src/writerai/resources/chat.py +++ b/src/writerai/resources/chat.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Type, Union, TypeVar, Iterable +from typing import Type, Union, TypeVar, Iterable from functools import partial from typing_extensions import Literal, overload From 8b393324d836a7c1ea087b96e9101edf9d5e15a2 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 11 Sep 2025 21:54:19 +0000 Subject: [PATCH 17/17] release: 2.3.2-rc1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 33 +++++++++++++++++++++++++++++++++ README.md | 4 ++-- pyproject.toml | 2 +- src/writerai/_version.py | 2 +- 5 files changed, 38 insertions(+), 5 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2d96c4d3..f1d45d57 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.3.1" + ".": "2.3.2-rc1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e813d08a..1cbcdb5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## 2.3.2-rc1 (2025-09-11) + +Full Changelog: [v2.3.1...v2.3.2-rc1](https://github.com/writer/writer-python/compare/v2.3.1...v2.3.2-rc1) + +### Features + +* improve future compat with pydantic v3 ([74315c4](https://github.com/writer/writer-python/commit/74315c493b0f439614d492378ae34fc0728c8bb1)) +* **types:** replace List[str] with SequenceNotStr in params ([2c1a7de](https://github.com/writer/writer-python/commit/2c1a7de9a61c13b20b7734ba4f87da6ca7771e30)) + + +### Bug Fixes + +* avoid newer type syntax ([4aec590](https://github.com/writer/writer-python/commit/4aec5902d7329039817f2049c299458fa8eb1381)) +* **client:** custom patch to prepare pydantic v3 ([8a26e46](https://github.com/writer/writer-python/commit/8a26e46ec365ea9905be7531bd80ebd9c74b129d)) + + +### Chores + +* **client:** format ([fa024a5](https://github.com/writer/writer-python/commit/fa024a58b0bc88104744f17279f5ca3819f28284)) +* **client:** update stop params in stream/parse to match chat ([8920408](https://github.com/writer/writer-python/commit/8920408285a5adfe7d0a416bc4539e42326b180e)) +* **internal:** add Sequence related utils ([40901e2](https://github.com/writer/writer-python/commit/40901e2ad2c45f6d8258df2e0666cc88c6c1fa0f)) +* **internal:** change ci workflow machines ([84dcbed](https://github.com/writer/writer-python/commit/84dcbedf80ab51ed3d4379839682b0c584041bb9)) +* **internal:** move mypy configurations to `pyproject.toml` file ([2518950](https://github.com/writer/writer-python/commit/251895049da0d7302cb37c599b0ca23dd0b6d470)) +* **internal:** update pyright exclude list ([815b794](https://github.com/writer/writer-python/commit/815b794df77ae9e20842db345988c93f1f077ee7)) +* **tests:** simplify `get_platform` test ([f1ddbb2](https://github.com/writer/writer-python/commit/f1ddbb236dbc6c1780eb1120e2fba20c0e4c921a)) +* update github action ([d81d1ec](https://github.com/writer/writer-python/commit/d81d1ec4fe56a7761fd5c3ad2afc65e8b12954fd)) + + +### Documentation + +* **api:** updates to API spec ([daf31d5](https://github.com/writer/writer-python/commit/daf31d587a7bc32c9debe961ac870d08fedef865)) +* **api:** updates to API spec ([5f8a109](https://github.com/writer/writer-python/commit/5f8a109801baff44a41313e2a4774ecc2c7e70bd)) + ## 2.3.1 (2025-08-20) Full Changelog: [v2.3.1-rc1...v2.3.1](https://github.com/writer/writer-python/compare/v2.3.1-rc1...v2.3.1) diff --git a/README.md b/README.md index b0ae7de7..ce698aeb 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ To install the package from PyPI, use `pip`: ```sh # install from PyPI -pip install writer-sdk +pip install --pre writer-sdk ``` ## Prequisites @@ -116,7 +116,7 @@ You can enable this by installing `aiohttp`: ```sh # install from PyPI -pip install writer-sdk[aiohttp] +pip install --pre writer-sdk[aiohttp] ``` Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`: diff --git a/pyproject.toml b/pyproject.toml index 34ede76d..6dc6a4bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "writer-sdk" -version = "2.3.1" +version = "2.3.2-rc1" description = "The official Python library for the writer API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/writerai/_version.py b/src/writerai/_version.py index fdf45740..8269c8fb 100644 --- a/src/writerai/_version.py +++ b/src/writerai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "writerai" -__version__ = "2.3.1" # x-release-please-version +__version__ = "2.3.2-rc1" # x-release-please-version