slot-flight 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. slot_flight-0.1.0/LICENSE +21 -0
  2. slot_flight-0.1.0/MANIFEST.in +5 -0
  3. slot_flight-0.1.0/PKG-INFO +176 -0
  4. slot_flight-0.1.0/README.md +141 -0
  5. slot_flight-0.1.0/pyproject.toml +72 -0
  6. slot_flight-0.1.0/setup.cfg +4 -0
  7. slot_flight-0.1.0/src/slot_flight/__init__.py +48 -0
  8. slot_flight-0.1.0/src/slot_flight/_streams.py +39 -0
  9. slot_flight-0.1.0/src/slot_flight/adapters/__init__.py +1 -0
  10. slot_flight-0.1.0/src/slot_flight/adapters/langchain.py +93 -0
  11. slot_flight-0.1.0/src/slot_flight/adapters/openai.py +68 -0
  12. slot_flight-0.1.0/src/slot_flight/adapters/openai_compatible.py +245 -0
  13. slot_flight-0.1.0/src/slot_flight/errors.py +24 -0
  14. slot_flight-0.1.0/src/slot_flight/frame.py +158 -0
  15. slot_flight-0.1.0/src/slot_flight/path.py +120 -0
  16. slot_flight-0.1.0/src/slot_flight/prompt.py +74 -0
  17. slot_flight-0.1.0/src/slot_flight/py.typed +1 -0
  18. slot_flight-0.1.0/src/slot_flight/slot/__init__.py +23 -0
  19. slot_flight-0.1.0/src/slot_flight/slot/execution/__init__.py +3 -0
  20. slot_flight-0.1.0/src/slot_flight/slot/execution/events.py +64 -0
  21. slot_flight-0.1.0/src/slot_flight/slot/execution/failures.py +69 -0
  22. slot_flight-0.1.0/src/slot_flight/slot/execution/flight.py +128 -0
  23. slot_flight-0.1.0/src/slot_flight/slot/execution/request.py +73 -0
  24. slot_flight-0.1.0/src/slot_flight/slot/execution/state.py +10 -0
  25. slot_flight-0.1.0/src/slot_flight/slot/execution/types.py +17 -0
  26. slot_flight-0.1.0/src/slot_flight/slot/execution/values.py +33 -0
  27. slot_flight-0.1.0/src/slot_flight/slot/object/__init__.py +24 -0
  28. slot_flight-0.1.0/src/slot_flight/slot/object/definition.py +119 -0
  29. slot_flight-0.1.0/src/slot_flight/slot/object/projections.py +44 -0
  30. slot_flight-0.1.0/src/slot_flight/slot/object/stream.py +110 -0
  31. slot_flight-0.1.0/src/slot_flight/slot/object/web.py +89 -0
  32. slot_flight-0.1.0/src/slot_flight/types.py +40 -0
  33. slot_flight-0.1.0/src/slot_flight.egg-info/PKG-INFO +176 -0
  34. slot_flight-0.1.0/src/slot_flight.egg-info/SOURCES.txt +35 -0
  35. slot_flight-0.1.0/src/slot_flight.egg-info/dependency_links.txt +1 -0
  36. slot_flight-0.1.0/src/slot_flight.egg-info/requires.txt +15 -0
  37. slot_flight-0.1.0/src/slot_flight.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Minho Jang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ include LICENSE
2
+ include README.md
3
+ prune examples
4
+ prune tests
5
+ global-exclude __pycache__ *.py[cod]
@@ -0,0 +1,176 @@
1
+ Metadata-Version: 2.4
2
+ Name: slot-flight
3
+ Version: 0.1.0
4
+ Summary: Slot-wise LLM generation and server-owned JSON assembly for Python.
5
+ Author: slot-flight contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/miinhho/slot-flight
8
+ Project-URL: Repository, https://github.com/miinhho/slot-flight
9
+ Project-URL: Issues, https://github.com/miinhho/slot-flight/issues
10
+ Keywords: llm,json,streaming,slot-generation
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: pydantic<3,>=2
24
+ Provides-Extra: langchain
25
+ Requires-Dist: langchain-core>=0.3; extra == "langchain"
26
+ Provides-Extra: openai
27
+ Requires-Dist: openai>=1; extra == "openai"
28
+ Provides-Extra: openai-compatible
29
+ Requires-Dist: httpx>=0.28; extra == "openai-compatible"
30
+ Provides-Extra: adapters
31
+ Requires-Dist: httpx>=0.28; extra == "adapters"
32
+ Requires-Dist: langchain-core>=0.3; extra == "adapters"
33
+ Requires-Dist: openai>=1; extra == "adapters"
34
+ Dynamic: license-file
35
+
36
+ # slot-flight Python
37
+
38
+ Python SDK for slot-wise LLM value streaming with server-owned JSON assembly.
39
+
40
+ This package implements the same slot frame protocol used by the TypeScript SDK.
41
+ The core engine is provider-independent, and the public object API is Pydantic
42
+ first. Provider/framework adapters are available for the OpenAI SDK,
43
+ OpenAI-compatible HTTP endpoints, and LangChain. Runnable examples live in
44
+ `examples/`.
45
+
46
+ Full Python SDK notes live in the
47
+ [Python SDK guide](../../docs/python/README.md).
48
+
49
+ ```py
50
+ import os
51
+
52
+ from openai import AsyncOpenAI
53
+ from pydantic import BaseModel, Field
54
+ from slot_flight import slot_object
55
+ from slot_flight.adapters.openai import stream_slot_object
56
+
57
+
58
+ class Triage(BaseModel):
59
+ summary: str = Field(description="Write one concise operational summary.")
60
+ tags: list[str] = Field(description="Write a JSON array of exactly 3 tags.")
61
+
62
+
63
+ openai = AsyncOpenAI(
64
+ api_key=os.getenv("API_KEY"),
65
+ base_url=os.getenv("API_BASE_URL"),
66
+ )
67
+
68
+ stream = stream_slot_object(
69
+ client=openai,
70
+ model=os.getenv("MODEL", "openai/gpt-oss-20b"),
71
+ messages=[{"role": "user", "content": "Classify this feedback."}],
72
+ output=slot_object(Triage),
73
+ )
74
+
75
+ async for slot in stream.completed_slot_stream():
76
+ print(slot.slot, slot.value)
77
+
78
+ result = await stream.final_object()
79
+ ```
80
+
81
+ ## Slot Object API
82
+
83
+ `slot_object()` accepts a Pydantic v2 model. Every generated leaf field must use
84
+ `Field(description=...)`; that description becomes the model-facing instruction
85
+ for the slot.
86
+
87
+ ```py
88
+ class Triage(BaseModel):
89
+ summary: str = Field(description="Write one concise operational summary.")
90
+ tags: list[str] = Field(description="Write a JSON array of exactly 3 tags.")
91
+ ```
92
+
93
+ String fields, string enums, and string literals use text slots. Other described
94
+ fields use JSON slots and are parsed before Pydantic validates the value. A
95
+ nested model without its own field description is expanded into nested slots; a
96
+ nested model with a description becomes one JSON slot.
97
+
98
+ Failed slot validation retries only the failed slots up to `max_retries`:
99
+
100
+ ```py
101
+ output = slot_object(Triage, max_retries=1)
102
+ ```
103
+
104
+ The object stream exposes the same views as the TypeScript SDK, using Python
105
+ method names:
106
+
107
+ ```py
108
+ async for event in stream.slot_event_stream():
109
+ ...
110
+
111
+ async for partial in stream.partial_object_stream():
112
+ ...
113
+
114
+ async for chunk in stream.to_sse(source="completed"):
115
+ ...
116
+
117
+ async for line in stream.to_ndjson(source="events"):
118
+ ...
119
+ ```
120
+
121
+ `final_object()`, `completed_slot_stream()`, `partial_object_stream()`, and
122
+ `slot_event_stream()` consume one underlying model run. After the run finishes,
123
+ later consumers replay cached events. A second live consumer is rejected while a
124
+ run is still active.
125
+
126
+ If you already have a slot event stream, wrap it with
127
+ `create_slot_object_event_stream()` to reuse the same object-stream views:
128
+
129
+ ```py
130
+ from slot_flight import create_slot_object_event_stream
131
+
132
+ stream = create_slot_object_event_stream(existing_events)
133
+ ```
134
+
135
+ ## HTTP Streaming
136
+
137
+ `to_sse()` and `to_ndjson()` are framework-neutral async iterators. In FastAPI or
138
+ Starlette, pass them to `StreamingResponse`:
139
+
140
+ ```py
141
+ from starlette.responses import StreamingResponse
142
+
143
+
144
+ async def route():
145
+ stream = stream_slot_object(...)
146
+ return StreamingResponse(
147
+ stream.to_sse(source="completed"),
148
+ media_type="text/event-stream",
149
+ )
150
+ ```
151
+
152
+ `source="completed"` emits completed slot updates plus retry/error/done events.
153
+ `source="partial"` emits draft object snapshots. `source="events"` emits the
154
+ low-level slot lifecycle events.
155
+
156
+ ## Examples
157
+
158
+ ```sh
159
+ uv run --extra openai examples/openai_compatible.py
160
+ uv run --extra openai-compatible examples/openai_compatible_httpx.py
161
+ uv run --extra langchain examples/langchain_runnable.py
162
+ ```
163
+
164
+ The OpenAI SDK example and raw OpenAI-compatible HTTP example both work with
165
+ endpoints such as NVIDIA NIM: set `API_KEY`, `API_BASE_URL`, and `MODEL` as
166
+ shown in the root `.env.example`.
167
+
168
+ ## Development
169
+
170
+ ```sh
171
+ uv sync --all-extras --dev
172
+ uv run ruff check .
173
+ uv run ty check
174
+ uv run pytest
175
+ uv build
176
+ ```
@@ -0,0 +1,141 @@
1
+ # slot-flight Python
2
+
3
+ Python SDK for slot-wise LLM value streaming with server-owned JSON assembly.
4
+
5
+ This package implements the same slot frame protocol used by the TypeScript SDK.
6
+ The core engine is provider-independent, and the public object API is Pydantic
7
+ first. Provider/framework adapters are available for the OpenAI SDK,
8
+ OpenAI-compatible HTTP endpoints, and LangChain. Runnable examples live in
9
+ `examples/`.
10
+
11
+ Full Python SDK notes live in the
12
+ [Python SDK guide](../../docs/python/README.md).
13
+
14
+ ```py
15
+ import os
16
+
17
+ from openai import AsyncOpenAI
18
+ from pydantic import BaseModel, Field
19
+ from slot_flight import slot_object
20
+ from slot_flight.adapters.openai import stream_slot_object
21
+
22
+
23
+ class Triage(BaseModel):
24
+ summary: str = Field(description="Write one concise operational summary.")
25
+ tags: list[str] = Field(description="Write a JSON array of exactly 3 tags.")
26
+
27
+
28
+ openai = AsyncOpenAI(
29
+ api_key=os.getenv("API_KEY"),
30
+ base_url=os.getenv("API_BASE_URL"),
31
+ )
32
+
33
+ stream = stream_slot_object(
34
+ client=openai,
35
+ model=os.getenv("MODEL", "openai/gpt-oss-20b"),
36
+ messages=[{"role": "user", "content": "Classify this feedback."}],
37
+ output=slot_object(Triage),
38
+ )
39
+
40
+ async for slot in stream.completed_slot_stream():
41
+ print(slot.slot, slot.value)
42
+
43
+ result = await stream.final_object()
44
+ ```
45
+
46
+ ## Slot Object API
47
+
48
+ `slot_object()` accepts a Pydantic v2 model. Every generated leaf field must use
49
+ `Field(description=...)`; that description becomes the model-facing instruction
50
+ for the slot.
51
+
52
+ ```py
53
+ class Triage(BaseModel):
54
+ summary: str = Field(description="Write one concise operational summary.")
55
+ tags: list[str] = Field(description="Write a JSON array of exactly 3 tags.")
56
+ ```
57
+
58
+ String fields, string enums, and string literals use text slots. Other described
59
+ fields use JSON slots and are parsed before Pydantic validates the value. A
60
+ nested model without its own field description is expanded into nested slots; a
61
+ nested model with a description becomes one JSON slot.
62
+
63
+ Failed slot validation retries only the failed slots up to `max_retries`:
64
+
65
+ ```py
66
+ output = slot_object(Triage, max_retries=1)
67
+ ```
68
+
69
+ The object stream exposes the same views as the TypeScript SDK, using Python
70
+ method names:
71
+
72
+ ```py
73
+ async for event in stream.slot_event_stream():
74
+ ...
75
+
76
+ async for partial in stream.partial_object_stream():
77
+ ...
78
+
79
+ async for chunk in stream.to_sse(source="completed"):
80
+ ...
81
+
82
+ async for line in stream.to_ndjson(source="events"):
83
+ ...
84
+ ```
85
+
86
+ `final_object()`, `completed_slot_stream()`, `partial_object_stream()`, and
87
+ `slot_event_stream()` consume one underlying model run. After the run finishes,
88
+ later consumers replay cached events. A second live consumer is rejected while a
89
+ run is still active.
90
+
91
+ If you already have a slot event stream, wrap it with
92
+ `create_slot_object_event_stream()` to reuse the same object-stream views:
93
+
94
+ ```py
95
+ from slot_flight import create_slot_object_event_stream
96
+
97
+ stream = create_slot_object_event_stream(existing_events)
98
+ ```
99
+
100
+ ## HTTP Streaming
101
+
102
+ `to_sse()` and `to_ndjson()` are framework-neutral async iterators. In FastAPI or
103
+ Starlette, pass them to `StreamingResponse`:
104
+
105
+ ```py
106
+ from starlette.responses import StreamingResponse
107
+
108
+
109
+ async def route():
110
+ stream = stream_slot_object(...)
111
+ return StreamingResponse(
112
+ stream.to_sse(source="completed"),
113
+ media_type="text/event-stream",
114
+ )
115
+ ```
116
+
117
+ `source="completed"` emits completed slot updates plus retry/error/done events.
118
+ `source="partial"` emits draft object snapshots. `source="events"` emits the
119
+ low-level slot lifecycle events.
120
+
121
+ ## Examples
122
+
123
+ ```sh
124
+ uv run --extra openai examples/openai_compatible.py
125
+ uv run --extra openai-compatible examples/openai_compatible_httpx.py
126
+ uv run --extra langchain examples/langchain_runnable.py
127
+ ```
128
+
129
+ The OpenAI SDK example and raw OpenAI-compatible HTTP example both work with
130
+ endpoints such as NVIDIA NIM: set `API_KEY`, `API_BASE_URL`, and `MODEL` as
131
+ shown in the root `.env.example`.
132
+
133
+ ## Development
134
+
135
+ ```sh
136
+ uv sync --all-extras --dev
137
+ uv run ruff check .
138
+ uv run ty check
139
+ uv run pytest
140
+ uv build
141
+ ```
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "slot-flight"
7
+ version = "0.1.0"
8
+ description = "Slot-wise LLM generation and server-owned JSON assembly for Python."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "slot-flight contributors" }]
13
+ keywords = ["llm", "json", "streaming", "slot-generation"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ "Typing :: Typed"
24
+ ]
25
+ dependencies = [
26
+ "pydantic>=2,<3"
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/miinhho/slot-flight"
31
+ Repository = "https://github.com/miinhho/slot-flight"
32
+ Issues = "https://github.com/miinhho/slot-flight/issues"
33
+
34
+ [project.optional-dependencies]
35
+ langchain = ["langchain-core>=0.3"]
36
+ openai = ["openai>=1"]
37
+ openai-compatible = ["httpx>=0.28"]
38
+ adapters = [
39
+ "httpx>=0.28",
40
+ "langchain-core>=0.3",
41
+ "openai>=1"
42
+ ]
43
+
44
+ [tool.setuptools.packages.find]
45
+ where = ["src"]
46
+
47
+ [tool.setuptools.package-data]
48
+ slot_flight = ["py.typed"]
49
+
50
+ [dependency-groups]
51
+ dev = [
52
+ "pytest>=8",
53
+ "ruff>=0.8",
54
+ "twine>=6",
55
+ "ty>=0.0.1a20"
56
+ ]
57
+
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["tests"]
60
+
61
+ [tool.ruff]
62
+ line-length = 88
63
+ target-version = "py310"
64
+
65
+ [tool.ruff.lint]
66
+ select = ["E", "F", "I", "UP"]
67
+
68
+ [tool.ruff.lint.per-file-ignores]
69
+ "src/slot_flight/prompt.py" = ["E501"]
70
+
71
+ [tool.ty.environment]
72
+ python-version = "3.10"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,48 @@
1
+ from .errors import (
2
+ SlotFlightConfigurationError,
3
+ SlotFlightError,
4
+ SlotFlightJsonParseError,
5
+ SlotFlightSlotProtocolError,
6
+ SlotFlightStreamError,
7
+ SlotFlightValidationError,
8
+ )
9
+ from .slot.execution import SlotFlight, slot_flight
10
+ from .slot.object import (
11
+ CompletedSlot,
12
+ SlotObjectEventSource,
13
+ SlotObjectOutput,
14
+ SlotObjectStream,
15
+ SlotObjectStreamFormat,
16
+ SlotObjectStreamSource,
17
+ create_slot_object_event_stream,
18
+ create_slot_object_stream,
19
+ slot_object,
20
+ )
21
+ from .types import (
22
+ SlotDefinition,
23
+ SlotFlightRequest,
24
+ SlotFrameRequest,
25
+ )
26
+
27
+ __all__ = [
28
+ "SlotDefinition",
29
+ "SlotFlight",
30
+ "SlotFlightConfigurationError",
31
+ "SlotFlightError",
32
+ "SlotFlightJsonParseError",
33
+ "SlotFlightRequest",
34
+ "SlotFlightSlotProtocolError",
35
+ "SlotFlightStreamError",
36
+ "SlotFlightValidationError",
37
+ "SlotFrameRequest",
38
+ "SlotObjectEventSource",
39
+ "SlotObjectOutput",
40
+ "SlotObjectStream",
41
+ "SlotObjectStreamFormat",
42
+ "SlotObjectStreamSource",
43
+ "CompletedSlot",
44
+ "create_slot_object_event_stream",
45
+ "create_slot_object_stream",
46
+ "slot_flight",
47
+ "slot_object",
48
+ ]
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import AsyncIterable, AsyncIterator, Iterable
5
+ from typing import Any, TypeVar, cast
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ async def iterate_stream(stream: Any, *, error_message: str) -> AsyncIterator[T]:
11
+ try:
12
+ if hasattr(stream, "__aiter__"):
13
+ async for item in cast(AsyncIterable[T], stream):
14
+ yield item
15
+ return
16
+
17
+ if isinstance(stream, Iterable):
18
+ for item in cast(Iterable[T], stream):
19
+ yield item
20
+ return
21
+
22
+ raise TypeError(error_message)
23
+ finally:
24
+ await close_stream(stream)
25
+
26
+
27
+ async def close_stream(stream: Any) -> None:
28
+ close = getattr(stream, "aclose", None)
29
+ if callable(close):
30
+ result = close()
31
+ if inspect.isawaitable(result):
32
+ await result
33
+ return
34
+
35
+ close = getattr(stream, "close", None)
36
+ if callable(close):
37
+ result = close()
38
+ if inspect.isawaitable(result):
39
+ await result
@@ -0,0 +1 @@
1
+ __all__: list[str] = []
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any
5
+
6
+ from slot_flight._streams import close_stream, iterate_stream
7
+ from slot_flight.slot.object import (
8
+ SlotObjectOutput,
9
+ SlotObjectStream,
10
+ create_slot_object_stream,
11
+ )
12
+ from slot_flight.types import SlotFlightRequest
13
+
14
+
15
+ def stream_slot_object(
16
+ *,
17
+ runnable: Any,
18
+ messages: Sequence[Any],
19
+ output: SlotObjectOutput,
20
+ **params: Any,
21
+ ) -> SlotObjectStream:
22
+ async def generate(request: SlotFlightRequest):
23
+ request_messages = [*messages, ("human", request.prompt)]
24
+
25
+ if hasattr(runnable, "astream"):
26
+ stream = runnable.astream(request_messages, **params)
27
+ chunks = iterate_stream(
28
+ stream,
29
+ error_message="LangChain stream must be iterable or async iterable.",
30
+ )
31
+ try:
32
+ async for chunk in chunks:
33
+ text = _chunk_text(chunk)
34
+ if text:
35
+ yield text
36
+ finally:
37
+ await close_stream(chunks)
38
+ return
39
+
40
+ if hasattr(runnable, "stream"):
41
+ stream = runnable.stream(request_messages, **params)
42
+ chunks = iterate_stream(
43
+ stream,
44
+ error_message="LangChain stream must be iterable or async iterable.",
45
+ )
46
+ try:
47
+ async for chunk in chunks:
48
+ text = _chunk_text(chunk)
49
+ if text:
50
+ yield text
51
+ finally:
52
+ await close_stream(chunks)
53
+ return
54
+
55
+ raise TypeError("LangChain runnable must expose stream() or astream().")
56
+
57
+ return create_slot_object_stream(output=output, generate=generate)
58
+
59
+
60
+ def _chunk_text(chunk: Any) -> str:
61
+ if isinstance(chunk, str):
62
+ return chunk
63
+
64
+ content = getattr(chunk, "content", None)
65
+ text = _content_text(content)
66
+ if text:
67
+ return text
68
+
69
+ if isinstance(chunk, dict):
70
+ return _content_text(chunk.get("content", ""))
71
+ return ""
72
+
73
+
74
+ def _content_text(content: Any) -> str:
75
+ if isinstance(content, str):
76
+ return content
77
+
78
+ if isinstance(content, list):
79
+ return "".join(_content_part_text(part) for part in content)
80
+
81
+ return ""
82
+
83
+
84
+ def _content_part_text(part: Any) -> str:
85
+ if isinstance(part, str):
86
+ return part
87
+
88
+ if isinstance(part, dict):
89
+ text = part.get("text", "")
90
+ return text if isinstance(text, str) else ""
91
+
92
+ text = getattr(part, "text", "")
93
+ return text if isinstance(text, str) else ""
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import Sequence
5
+ from typing import Any
6
+
7
+ from slot_flight._streams import close_stream, iterate_stream
8
+ from slot_flight.slot.object import (
9
+ SlotObjectOutput,
10
+ SlotObjectStream,
11
+ create_slot_object_stream,
12
+ )
13
+ from slot_flight.types import SlotFlightRequest
14
+
15
+
16
+ def stream_slot_object(
17
+ *,
18
+ client: Any,
19
+ model: str,
20
+ messages: Sequence[dict[str, Any]],
21
+ output: SlotObjectOutput,
22
+ **params: Any,
23
+ ) -> SlotObjectStream:
24
+ async def generate(request: SlotFlightRequest):
25
+ request_messages = [
26
+ *messages,
27
+ {
28
+ "role": "user",
29
+ "content": request.prompt,
30
+ },
31
+ ]
32
+ stream = client.chat.completions.create(
33
+ model=model,
34
+ messages=request_messages,
35
+ stream=True,
36
+ **params,
37
+ )
38
+ if inspect.isawaitable(stream):
39
+ stream = await stream
40
+
41
+ chunks = iterate_stream(
42
+ stream,
43
+ error_message="OpenAI stream must be iterable or async iterable.",
44
+ )
45
+ try:
46
+ async for chunk in chunks:
47
+ text = _chunk_text(chunk)
48
+ if text:
49
+ yield text
50
+ finally:
51
+ await close_stream(chunks)
52
+
53
+ return create_slot_object_stream(output=output, generate=generate)
54
+
55
+
56
+ def _chunk_text(chunk: Any) -> str:
57
+ choices = _get(chunk, "choices", [])
58
+ if not choices:
59
+ return ""
60
+ delta = _get(choices[0], "delta", None)
61
+ content = _get(delta, "content", "")
62
+ return content if isinstance(content, str) else ""
63
+
64
+
65
+ def _get(value: Any, key: str, default: Any) -> Any:
66
+ if isinstance(value, dict):
67
+ return value.get(key, default)
68
+ return getattr(value, key, default)