Skip to content

Commit 0183932

Browse files
release: 2.0.0-beta.3 (#93)
* fix(client): close streams without requiring full consumption * chore(internal/tests): avoid race condition with implicit client cleanup * chore(internal): grammar fix (it's -> its) * chore(package): drop Python 3.8 support * fix: compat with Python 3.14 * fix(compat): update signatures of `model_dump` and `model_dump_json` for Pydantic v1 * release: 2.0.0-beta.3 --------- Co-authored-by: stainless-app[bot] <142633134+stainless-app[bot]@users.noreply.github.com>
1 parent f778511 commit 0183932

File tree

11 files changed

+272
-228
lines changed

11 files changed

+272
-228
lines changed

.release-please-manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
{
2-
".": "2.0.0-beta.2"
2+
".": "2.0.0-beta.3"
33
}

CHANGELOG.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
11
# Changelog
22

3+
## 2.0.0-beta.3 (2025-11-11)
4+
5+
Full Changelog: [v2.0.0-beta.2...v2.0.0-beta.3](https://github.com/replicate/replicate-python-beta/compare/v2.0.0-beta.2...v2.0.0-beta.3)
6+
7+
### Bug Fixes
8+
9+
* **client:** close streams without requiring full consumption ([73bd0ab](https://github.com/replicate/replicate-python-beta/commit/73bd0ab734be57dab38fe3c59d43e016429f16ed))
10+
* compat with Python 3.14 ([ad4b6b3](https://github.com/replicate/replicate-python-beta/commit/ad4b6b38c97cab6710f5601578eed7410b0d37a1))
11+
* **compat:** update signatures of `model_dump` and `model_dump_json` for Pydantic v1 ([56fbff8](https://github.com/replicate/replicate-python-beta/commit/56fbff8ad39623efa3cba2db497e0e084c542e3d))
12+
13+
14+
### Chores
15+
16+
* **internal/tests:** avoid race condition with implicit client cleanup ([2e35773](https://github.com/replicate/replicate-python-beta/commit/2e3577300dcb0222c1d1d9e830e63d34b3c13296))
17+
* **internal:** grammar fix (it's -&gt; its) ([7f6ba66](https://github.com/replicate/replicate-python-beta/commit/7f6ba660cb0ef32ec09b51b2b59256eaf3bc973a))
18+
* **package:** drop Python 3.8 support ([9c1211c](https://github.com/replicate/replicate-python-beta/commit/9c1211c67a28d3aa431b7cbcb553539e8d6d5f2c))
19+
320
## 2.0.0-beta.2 (2025-10-23)
421

522
Full Changelog: [v2.0.0-beta.1...v2.0.0-beta.2](https://github.com/replicate/replicate-python-beta/compare/v2.0.0-beta.1...v2.0.0-beta.2)

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,7 @@ print(replicate.__version__)
689689

690690
## Requirements
691691

692-
Python 3.8 or higher.
692+
Python 3.9 or higher.
693693

694694
## Contributing
695695

pyproject.toml

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "replicate"
3-
version = "2.0.0-beta.2"
3+
version = "2.0.0-beta.3"
44
description = "The official Python library for the replicate API"
55
dynamic = ["readme"]
66
license = "Apache-2.0"
@@ -16,11 +16,10 @@ dependencies = [
1616
"sniffio",
1717
"packaging>=25.0",
1818
]
19-
requires-python = ">= 3.8"
19+
requires-python = ">= 3.9"
2020
classifiers = [
2121
"Typing :: Typed",
2222
"Intended Audience :: Developers",
23-
"Programming Language :: Python :: 3.8",
2423
"Programming Language :: Python :: 3.9",
2524
"Programming Language :: Python :: 3.10",
2625
"Programming Language :: Python :: 3.11",
@@ -142,7 +141,7 @@ filterwarnings = [
142141
# there are a couple of flags that are still disabled by
143142
# default in strict mode as they are experimental and niche.
144143
typeCheckingMode = "strict"
145-
pythonVersion = "3.8"
144+
pythonVersion = "3.9"
146145

147146
exclude = [
148147
"_dev",

src/replicate/_models.py

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import os
44
import inspect
5+
import weakref
56
from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast
67
from datetime import date, datetime
78
from typing_extensions import (
@@ -256,32 +257,41 @@ def model_dump(
256257
mode: Literal["json", "python"] | str = "python",
257258
include: IncEx | None = None,
258259
exclude: IncEx | None = None,
260+
context: Any | None = None,
259261
by_alias: bool | None = None,
260262
exclude_unset: bool = False,
261263
exclude_defaults: bool = False,
262264
exclude_none: bool = False,
265+
exclude_computed_fields: bool = False,
263266
round_trip: bool = False,
264267
warnings: bool | Literal["none", "warn", "error"] = True,
265-
context: dict[str, Any] | None = None,
266-
serialize_as_any: bool = False,
267268
fallback: Callable[[Any], Any] | None = None,
269+
serialize_as_any: bool = False,
268270
) -> dict[str, Any]:
269271
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
270272
271273
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
272274
273275
Args:
274276
mode: The mode in which `to_python` should run.
275-
If mode is 'json', the dictionary will only contain JSON serializable types.
276-
If mode is 'python', the dictionary may contain any Python objects.
277-
include: A list of fields to include in the output.
278-
exclude: A list of fields to exclude from the output.
277+
If mode is 'json', the output will only contain JSON serializable types.
278+
If mode is 'python', the output may contain non-JSON-serializable Python objects.
279+
include: A set of fields to include in the output.
280+
exclude: A set of fields to exclude from the output.
281+
context: Additional context to pass to the serializer.
279282
by_alias: Whether to use the field's alias in the dictionary key if defined.
280-
exclude_unset: Whether to exclude fields that are unset or None from the output.
281-
exclude_defaults: Whether to exclude fields that are set to their default value from the output.
282-
exclude_none: Whether to exclude fields that have a value of `None` from the output.
283-
round_trip: Whether to enable serialization and deserialization round-trip support.
284-
warnings: Whether to log warnings when invalid fields are encountered.
283+
exclude_unset: Whether to exclude fields that have not been explicitly set.
284+
exclude_defaults: Whether to exclude fields that are set to their default value.
285+
exclude_none: Whether to exclude fields that have a value of `None`.
286+
exclude_computed_fields: Whether to exclude computed fields.
287+
While this can be useful for round-tripping, it is usually recommended to use the dedicated
288+
`round_trip` parameter instead.
289+
round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
290+
warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
291+
"error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
292+
fallback: A function to call when an unknown value is encountered. If not provided,
293+
a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
294+
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
285295
286296
Returns:
287297
A dictionary representation of the model.
@@ -298,6 +308,8 @@ def model_dump(
298308
raise ValueError("serialize_as_any is only supported in Pydantic v2")
299309
if fallback is not None:
300310
raise ValueError("fallback is only supported in Pydantic v2")
311+
if exclude_computed_fields != False:
312+
raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
301313
dumped = super().dict( # pyright: ignore[reportDeprecated]
302314
include=include,
303315
exclude=exclude,
@@ -314,15 +326,17 @@ def model_dump_json(
314326
self,
315327
*,
316328
indent: int | None = None,
329+
ensure_ascii: bool = False,
317330
include: IncEx | None = None,
318331
exclude: IncEx | None = None,
332+
context: Any | None = None,
319333
by_alias: bool | None = None,
320334
exclude_unset: bool = False,
321335
exclude_defaults: bool = False,
322336
exclude_none: bool = False,
337+
exclude_computed_fields: bool = False,
323338
round_trip: bool = False,
324339
warnings: bool | Literal["none", "warn", "error"] = True,
325-
context: dict[str, Any] | None = None,
326340
fallback: Callable[[Any], Any] | None = None,
327341
serialize_as_any: bool = False,
328342
) -> str:
@@ -354,6 +368,10 @@ def model_dump_json(
354368
raise ValueError("serialize_as_any is only supported in Pydantic v2")
355369
if fallback is not None:
356370
raise ValueError("fallback is only supported in Pydantic v2")
371+
if ensure_ascii != False:
372+
raise ValueError("ensure_ascii is only supported in Pydantic v2")
373+
if exclude_computed_fields != False:
374+
raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
357375
return super().json( # type: ignore[reportDeprecated]
358376
indent=indent,
359377
include=include,
@@ -573,6 +591,9 @@ class CachedDiscriminatorType(Protocol):
573591
__discriminator__: DiscriminatorDetails
574592

575593

594+
DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary()
595+
596+
576597
class DiscriminatorDetails:
577598
field_name: str
578599
"""The name of the discriminator field in the variant class, e.g.
@@ -615,8 +636,9 @@ def __init__(
615636

616637

617638
def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
618-
if isinstance(union, CachedDiscriminatorType):
619-
return union.__discriminator__
639+
cached = DISCRIMINATOR_CACHE.get(union)
640+
if cached is not None:
641+
return cached
620642

621643
discriminator_field_name: str | None = None
622644

@@ -669,7 +691,7 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any,
669691
discriminator_field=discriminator_field_name,
670692
discriminator_alias=discriminator_alias,
671693
)
672-
cast(CachedDiscriminatorType, union).__discriminator__ = details
694+
DISCRIMINATOR_CACHE.setdefault(union, details)
673695
return details
674696

675697

src/replicate/_streaming.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,8 @@ def __stream__(self) -> Iterator[_T]:
5757
for sse in iterator:
5858
yield process_data(data=sse.json(), cast_to=cast_to, response=response)
5959

60-
# Ensure the entire stream is consumed
61-
for _sse in iterator:
62-
...
60+
# As we might not fully consume the response stream, we need to close it explicitly
61+
response.close()
6362

6463
def __enter__(self) -> Self:
6564
return self
@@ -121,9 +120,8 @@ async def __stream__(self) -> AsyncIterator[_T]:
121120
async for sse in iterator:
122121
yield process_data(data=sse.json(), cast_to=cast_to, response=response)
123122

124-
# Ensure the entire stream is consumed
125-
async for _sse in iterator:
126-
...
123+
# As we might not fully consume the response stream, we need to close it explicitly
124+
await response.aclose()
127125

128126
async def __aenter__(self) -> Self:
129127
return self

src/replicate/_utils/_sync.py

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
from __future__ import annotations
22

3-
import sys
43
import asyncio
54
import functools
6-
import contextvars
7-
from typing import Any, TypeVar, Callable, Awaitable
5+
from typing import TypeVar, Callable, Awaitable
86
from typing_extensions import ParamSpec
97

108
import anyio
@@ -15,34 +13,11 @@
1513
T_ParamSpec = ParamSpec("T_ParamSpec")
1614

1715

18-
if sys.version_info >= (3, 9):
19-
_asyncio_to_thread = asyncio.to_thread
20-
else:
21-
# backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
22-
# for Python 3.8 support
23-
async def _asyncio_to_thread(
24-
func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
25-
) -> Any:
26-
"""Asynchronously run function *func* in a separate thread.
27-
28-
Any *args and **kwargs supplied for this function are directly passed
29-
to *func*. Also, the current :class:`contextvars.Context` is propagated,
30-
allowing context variables from the main thread to be accessed in the
31-
separate thread.
32-
33-
Returns a coroutine that can be awaited to get the eventual result of *func*.
34-
"""
35-
loop = asyncio.events.get_running_loop()
36-
ctx = contextvars.copy_context()
37-
func_call = functools.partial(ctx.run, func, *args, **kwargs)
38-
return await loop.run_in_executor(None, func_call)
39-
40-
4116
async def to_thread(
4217
func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
4318
) -> T_Retval:
4419
if sniffio.current_async_library() == "asyncio":
45-
return await _asyncio_to_thread(func, *args, **kwargs)
20+
return await asyncio.to_thread(func, *args, **kwargs)
4621

4722
return await anyio.to_thread.run_sync(
4823
functools.partial(func, *args, **kwargs),
@@ -53,10 +28,7 @@ async def to_thread(
5328
def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]:
5429
"""
5530
Take a blocking function and create an async one that receives the same
56-
positional and keyword arguments. For python version 3.9 and above, it uses
57-
asyncio.to_thread to run the function in a separate thread. For python version
58-
3.8, it uses locally defined copy of the asyncio.to_thread function which was
59-
introduced in python 3.9.
31+
positional and keyword arguments.
6032
6133
Usage:
6234

src/replicate/_utils/_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]:
133133
# Type safe methods for narrowing types with TypeVars.
134134
# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
135135
# however this cause Pyright to rightfully report errors. As we know we don't
136-
# care about the contained types we can safely use `object` in it's place.
136+
# care about the contained types we can safely use `object` in its place.
137137
#
138138
# There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
139139
# `is_*` is for when you're dealing with an unknown input

src/replicate/_version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
22

33
__title__ = "replicate"
4-
__version__ = "2.0.0-beta.2" # x-release-please-version
4+
__version__ = "2.0.0-beta.3" # x-release-please-version

0 commit comments

Comments
 (0)