Skip to content

The agent engineering platform.

fix(core): type text stream projections (#39170)

Nick Hollona78daf023365
diff --git a/libs/core/langchain_core/language_models/chat_model_stream.py b/libs/core/langchain_core/language_models/chat_model_stream.py
index 045e9a0375..612a6faf34 100644
--- a/libs/core/langchain_core/language_models/chat_model_stream.py
+++ b/libs/core/langchain_core/language_models/chat_model_stream.py
@@ -283,16 +283,47 @@ class SyncProjection(_ProjectionBase):
class SyncTextProjection(SyncProjection):
"""String-specialized sync projection.
- Adds `__str__`, `__bool__`, `__repr__` for ergonomic use with
- `.text` and `.reasoning` projections.
+ Adds typed string producers and consumers, plus `__str__`, `__bool__`,
+ `__repr__` for ergonomic use with `.text` and `.reasoning` projections.
"""
__slots__ = ()
+ def push(self, delta: str) -> None:
+ """Append a text delta."""
+ if not isinstance(cast("Any", delta), str):
+ msg = "SyncTextProjection requires a string delta"
+ raise TypeError(msg)
+ super().push(delta)
+
+ def complete(self, final_value: str) -> None:
+ """Set the final accumulated text and mark the projection as done."""
+ if not isinstance(cast("Any", final_value), str):
+ msg = "SyncTextProjection requires a string final value"
+ raise TypeError(msg)
+ super().complete(final_value)
+
+ def __iter__(self) -> Iterator[str]:
+ """Yield text deltas, raising if a producer supplied a non-string value."""
+ for delta in super().__iter__():
+ if not isinstance(delta, str):
+ msg = "SyncTextProjection received a non-string delta"
+ raise TypeError(msg)
+ yield delta
+
+ def get(self) -> str:
+ """Drain and return the full accumulated string, or empty if unfinished."""
+ value = super().get()
+ if value is None:
+ return ""
+ if not isinstance(value, str):
+ msg = "SyncTextProjection received a non-string final value"
+ raise TypeError(msg)
+ return value
+
def __str__(self) -> str:
"""Drain and return the full accumulated string."""
- val = self.get()
- return val if val is not None else ""
+ return self.get()
def __bool__(self) -> bool:
"""Return whether any deltas have been pushed."""
@@ -465,6 +496,58 @@ class _AsyncProjectionIterator:
await proj._event.wait() # noqa: SLF001
+class _AsyncTextProjectionIterator(_AsyncProjectionIterator):
+ """Async iterator over an `AsyncTextProjection`'s text deltas."""
+
+ __slots__ = ()
+
+ async def __anext__(self) -> str:
+ """Return the next text delta."""
+ item = await super().__anext__()
+ if not isinstance(item, str):
+ msg = "AsyncTextProjection received a non-string delta"
+ raise TypeError(msg)
+ return item
+
+
+class AsyncTextProjection(AsyncProjection):
+ """String-specialized async projection for `.text` and `.reasoning`."""
+
+ __slots__ = ()
+
+ def push(self, delta: str) -> None:
+ """Append a text delta and notify waiters."""
+ if not isinstance(cast("Any", delta), str):
+ msg = "AsyncTextProjection requires a string delta"
+ raise TypeError(msg)
+ super().push(delta)
+
+ def complete(self, final_value: str) -> None:
+ """Set the final accumulated text and notify waiters."""
+ if not isinstance(cast("Any", final_value), str):
+ msg = "AsyncTextProjection requires a string final value"
+ raise TypeError(msg)
+ super().complete(final_value)
+
+ def __aiter__(self) -> _AsyncTextProjectionIterator:
+ """Return an async iterator over text deltas."""
+ return _AsyncTextProjectionIterator(self)
+
+ def __await__(self) -> Generator[Any, None, str]:
+ """Await the full accumulated text."""
+ return self._await_text_impl().__await__()
+
+ async def _await_text_impl(self) -> str:
+ """Return accumulated text or raise if the final value is not a string."""
+ value = await self._await_impl()
+ if value is None:
+ return ""
+ if not isinstance(value, str):
+ msg = "AsyncTextProjection received a non-string final value"
+ raise TypeError(msg)
+ return value
+
+
# ---------------------------------------------------------------------------
# Sync stream
# ---------------------------------------------------------------------------
@@ -1222,8 +1305,8 @@ class AsyncChatModelStream(_ChatModelStreamBase):
async-iterable (`async for event in stream`).
"""
- _text_proj: AsyncProjection
- _reasoning_proj: AsyncProjection
+ _text_proj: AsyncTextProjection
+ _reasoning_proj: AsyncTextProjection
_tool_calls_proj: AsyncProjection
def __init__( # noqa: D107
@@ -1234,8 +1317,8 @@ class AsyncChatModelStream(_ChatModelStreamBase):
message_id: str | None = None,
) -> None:
super().__init__(namespace=namespace, node=node, message_id=message_id)
- self._text_proj = AsyncProjection()
- self._reasoning_proj = AsyncProjection()
+ self._text_proj = AsyncTextProjection()
+ self._reasoning_proj = AsyncTextProjection()
self._tool_calls_proj = AsyncProjection()
self._output_proj = AsyncProjection()
self._events_proj = AsyncProjection()
@@ -1285,12 +1368,12 @@ class AsyncChatModelStream(_ChatModelStreamBase):
# -- Public projections ------------------------------------------------
@property
- def text(self) -> AsyncProjection:
- """Text content — async iterable of deltas, awaitable for full."""
+ def text(self) -> AsyncTextProjection:
+ """Text content — async iterable of `str` deltas, awaitable for full text."""
return self._text_proj
@property
- def reasoning(self) -> AsyncProjection:
+ def reasoning(self) -> AsyncTextProjection:
"""Reasoning content — same interface as :attr:`text`."""
return self._reasoning_proj
@@ -1435,6 +1518,7 @@ class AsyncChatModelStream(_ChatModelStreamBase):
__all__ = [
"AsyncChatModelStream",
"AsyncProjection",
+ "AsyncTextProjection",
"ChatModelStream",
"SyncProjection",
"SyncTextProjection",
diff --git a/libs/core/tests/unit_tests/language_models/test_chat_model_stream.py b/libs/core/tests/unit_tests/language_models/test_chat_model_stream.py
index 1230e2b23c..534623bc9b 100644
--- a/libs/core/tests/unit_tests/language_models/test_chat_model_stream.py
+++ b/libs/core/tests/unit_tests/language_models/test_chat_model_stream.py
@@ -6,10 +6,12 @@ import asyncio
from typing import TYPE_CHECKING, Any, cast
import pytest
+from typing_extensions import assert_type
from langchain_core.language_models.chat_model_stream import (
AsyncChatModelStream,
AsyncProjection,
+ AsyncTextProjection,
ChatModelStream,
SyncProjection,
SyncTextProjection,
@@ -93,6 +95,24 @@ class TestSyncTextProjection:
proj.complete("Hello world")
assert str(proj) == "Hello world"
+ def test_get_before_completion_is_empty(self) -> None:
+ assert SyncTextProjection().get() == ""
+
+ def test_non_string_values_are_rejected_by_producers(self) -> None:
+ delta_proj = SyncTextProjection()
+ with pytest.raises(TypeError, match="requires a string delta"):
+ delta_proj.push(cast("str", 1))
+
+ final_proj = SyncTextProjection()
+ with pytest.raises(TypeError, match="requires a string final value"):
+ final_proj.complete(cast("str", 1))
+
+ def test_static_types(self) -> None:
+ stream = ChatModelStream()
+ for delta in stream.text:
+ assert_type(delta, str)
+ assert_type(stream.text.get(), str)
+
def test_str_with_pump(self) -> None:
proj = SyncTextProjection()
done = False
@@ -291,6 +311,37 @@ class TestAsyncProjection:
assert message.content == [{"type": "text", "text": "hello world", "index": 0}]
+class TestAsyncTextProjection:
+ """Test AsyncTextProjection string consumers."""
+
+ @pytest.mark.asyncio
+ async def test_async_iter_and_await(self) -> None:
+ proj = AsyncTextProjection()
+ proj.push("Hello")
+ proj.push(" world")
+ proj.complete("Hello world")
+ assert [delta async for delta in proj] == ["Hello", " world"]
+ assert await proj == "Hello world"
+
+ @pytest.mark.asyncio
+ async def test_non_string_values_are_rejected_by_producers(self) -> None:
+ delta_proj = AsyncTextProjection()
+ with pytest.raises(TypeError, match="requires a string delta"):
+ delta_proj.push(cast("str", 1))
+
+ final_proj = AsyncTextProjection()
+ with pytest.raises(TypeError, match="requires a string final value"):
+ final_proj.complete(cast("str", 1))
+
+ @pytest.mark.asyncio
+ async def test_static_types(self) -> None:
+ stream = AsyncChatModelStream()
+ stream.dispatch({"event": "message-finish"})
+ async for delta in stream.text:
+ assert_type(delta, str)
+ assert_type(await stream.text, str)
+
+
# ---------------------------------------------------------------------------
# ChatModelStream unit tests
# ---------------------------------------------------------------------------