|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, Union, Iterator, Optional |
| 4 | +from collections.abc import AsyncIterator |
| 5 | +from typing_extensions import Unpack |
| 6 | + |
| 7 | +from replicate.lib._files import FileEncodingStrategy |
| 8 | +from replicate.types.prediction_create_params import PredictionCreateParamsWithoutVersion |
| 9 | + |
| 10 | +from ..types import PredictionCreateParams |
| 11 | +from ._models import Model, Version, ModelVersionIdentifier, resolve_reference |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from .._client import Replicate, AsyncReplicate |
| 15 | + |
| 16 | + |
| 17 | +def stream( |
| 18 | + client: "Replicate", |
| 19 | + ref: Union[Model, Version, ModelVersionIdentifier, str], |
| 20 | + *, |
| 21 | + file_encoding_strategy: Optional["FileEncodingStrategy"] = None, |
| 22 | + **params: Unpack[PredictionCreateParamsWithoutVersion], |
| 23 | +) -> Iterator[str]: |
| 24 | + """ |
| 25 | + Stream output from a model prediction. |
| 26 | +
|
| 27 | + This creates a prediction and returns an iterator that yields output chunks |
| 28 | + as they become available via Server-Sent Events (SSE). |
| 29 | +
|
| 30 | + Args: |
| 31 | + client: The Replicate client instance |
| 32 | + ref: Reference to the model or version to run. Can be: |
| 33 | + - A string containing a version ID |
| 34 | + - A string with owner/name format (e.g. "replicate/hello-world") |
| 35 | + - A string with owner/name:version format |
| 36 | + - A Model instance |
| 37 | + - A Version instance |
| 38 | + - A ModelVersionIdentifier dictionary |
| 39 | + file_encoding_strategy: Strategy for encoding file inputs |
| 40 | + **params: Additional parameters including the required "input" dictionary |
| 41 | +
|
| 42 | + Yields: |
| 43 | + str: Output chunks from the model as they become available |
| 44 | +
|
| 45 | + Raises: |
| 46 | + ValueError: If the reference format is invalid |
| 47 | + ReplicateError: If the prediction fails or streaming is not available |
| 48 | + """ |
| 49 | + # Resolve ref to its components |
| 50 | + try: |
| 51 | + version, owner, name, version_id = resolve_reference(ref) |
| 52 | + except ValueError: |
| 53 | + # If resolution fails, treat it as a version ID if it's a string |
| 54 | + if isinstance(ref, str): |
| 55 | + version_id = ref |
| 56 | + owner = name = None |
| 57 | + else: |
| 58 | + raise |
| 59 | + |
| 60 | + # Create prediction |
| 61 | + prediction = None |
| 62 | + if version_id is not None: |
| 63 | + params_with_version: PredictionCreateParams = {**params, "version": version_id} |
| 64 | + prediction = client.predictions.create(file_encoding_strategy=file_encoding_strategy, **params_with_version) |
| 65 | + elif owner and name: |
| 66 | + prediction = client.models.predictions.create( |
| 67 | + file_encoding_strategy=file_encoding_strategy, model_owner=owner, model_name=name, **params |
| 68 | + ) |
| 69 | + else: |
| 70 | + if isinstance(ref, str): |
| 71 | + params_with_version = {**params, "version": ref} |
| 72 | + prediction = client.predictions.create(file_encoding_strategy=file_encoding_strategy, **params_with_version) |
| 73 | + else: |
| 74 | + raise ValueError( |
| 75 | + f"Invalid reference format: {ref}. Expected a model name ('owner/name'), " |
| 76 | + "a version ID, a Model object, a Version object, or a ModelVersionIdentifier." |
| 77 | + ) |
| 78 | + |
| 79 | + # Check if streaming URL is available |
| 80 | + if not prediction.urls or not prediction.urls.stream: |
| 81 | + raise ValueError("Model does not support streaming. The prediction URLs do not include a stream endpoint.") |
| 82 | + |
| 83 | + # Make SSE request to the stream URL |
| 84 | + stream_url = prediction.urls.stream |
| 85 | + |
| 86 | + with client._client.stream( |
| 87 | + "GET", |
| 88 | + stream_url, |
| 89 | + headers={ |
| 90 | + "Accept": "text/event-stream", |
| 91 | + "Cache-Control": "no-store", |
| 92 | + }, |
| 93 | + timeout=None, # No timeout for streaming |
| 94 | + ) as response: |
| 95 | + response.raise_for_status() |
| 96 | + |
| 97 | + # Parse SSE events and yield output chunks |
| 98 | + decoder = client._make_sse_decoder() |
| 99 | + for sse in decoder.iter_bytes(response.iter_bytes()): |
| 100 | + # The SSE data contains the output chunks |
| 101 | + if sse.data: |
| 102 | + yield sse.data |
| 103 | + |
| 104 | + |
| 105 | +async def async_stream( |
| 106 | + client: "AsyncReplicate", |
| 107 | + ref: Union[Model, Version, ModelVersionIdentifier, str], |
| 108 | + *, |
| 109 | + file_encoding_strategy: Optional["FileEncodingStrategy"] = None, |
| 110 | + **params: Unpack[PredictionCreateParamsWithoutVersion], |
| 111 | +) -> AsyncIterator[str]: |
| 112 | + """ |
| 113 | + Async stream output from a model prediction. |
| 114 | +
|
| 115 | + This creates a prediction and returns an async iterator that yields output chunks |
| 116 | + as they become available via Server-Sent Events (SSE). |
| 117 | +
|
| 118 | + Args: |
| 119 | + client: The AsyncReplicate client instance |
| 120 | + ref: Reference to the model or version to run |
| 121 | + file_encoding_strategy: Strategy for encoding file inputs |
| 122 | + **params: Additional parameters including the required "input" dictionary |
| 123 | +
|
| 124 | + Yields: |
| 125 | + str: Output chunks from the model as they become available |
| 126 | +
|
| 127 | + Raises: |
| 128 | + ValueError: If the reference format is invalid |
| 129 | + ReplicateError: If the prediction fails or streaming is not available |
| 130 | + """ |
| 131 | + # Resolve ref to its components |
| 132 | + try: |
| 133 | + version, owner, name, version_id = resolve_reference(ref) |
| 134 | + except ValueError: |
| 135 | + # If resolution fails, treat it as a version ID if it's a string |
| 136 | + if isinstance(ref, str): |
| 137 | + version_id = ref |
| 138 | + owner = name = None |
| 139 | + else: |
| 140 | + raise |
| 141 | + |
| 142 | + # Create prediction |
| 143 | + prediction = None |
| 144 | + if version_id is not None: |
| 145 | + params_with_version: PredictionCreateParams = {**params, "version": version_id} |
| 146 | + prediction = await client.predictions.create( |
| 147 | + file_encoding_strategy=file_encoding_strategy, **params_with_version |
| 148 | + ) |
| 149 | + elif owner and name: |
| 150 | + prediction = await client.models.predictions.create( |
| 151 | + file_encoding_strategy=file_encoding_strategy, model_owner=owner, model_name=name, **params |
| 152 | + ) |
| 153 | + else: |
| 154 | + if isinstance(ref, str): |
| 155 | + params_with_version = {**params, "version": ref} |
| 156 | + prediction = await client.predictions.create( |
| 157 | + file_encoding_strategy=file_encoding_strategy, **params_with_version |
| 158 | + ) |
| 159 | + else: |
| 160 | + raise ValueError( |
| 161 | + f"Invalid reference format: {ref}. Expected a model name ('owner/name'), " |
| 162 | + "a version ID, a Model object, a Version object, or a ModelVersionIdentifier." |
| 163 | + ) |
| 164 | + |
| 165 | + # Check if streaming URL is available |
| 166 | + if not prediction.urls or not prediction.urls.stream: |
| 167 | + raise ValueError("Model does not support streaming. The prediction URLs do not include a stream endpoint.") |
| 168 | + |
| 169 | + # Make SSE request to the stream URL |
| 170 | + stream_url = prediction.urls.stream |
| 171 | + |
| 172 | + async with client._client.stream( |
| 173 | + "GET", |
| 174 | + stream_url, |
| 175 | + headers={ |
| 176 | + "Accept": "text/event-stream", |
| 177 | + "Cache-Control": "no-store", |
| 178 | + }, |
| 179 | + timeout=None, # No timeout for streaming |
| 180 | + ) as response: |
| 181 | + response.raise_for_status() |
| 182 | + |
| 183 | + # Parse SSE events and yield output chunks |
| 184 | + decoder = client._make_sse_decoder() |
| 185 | + async for sse in decoder.aiter_bytes(response.aiter_bytes()): |
| 186 | + # The SSE data contains the output chunks |
| 187 | + if sse.data: |
| 188 | + yield sse.data |
0 commit comments