{"record":{"id":"dbda1344aabe1d9b","repo":"langchain-ai/langchain","slug":"cannot-stream-a-coroutine-function-synchronously-u","errorCode":null,"errorMessage":"Cannot stream a coroutine function synchronously.Use `astream` instead.","messagePattern":"Cannot stream a coroutine function synchronously\\.Use `astream` instead\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/runnables/base.py","lineNumber":5426,"sourceCode":"    def transform(\n        self,\n        input: Iterator[Input],\n        config: RunnableConfig | None = None,\n        **kwargs: Any | None,\n    ) -> Iterator[Output]:\n        if hasattr(self, \"func\"):\n            yield from self._transform_stream_with_config(\n                input,\n                self._transform,\n                ensure_config(config),\n                **kwargs,\n            )\n        else:\n            msg = (\n                \"Cannot stream a coroutine function synchronously.\"\n                \"Use `astream` instead.\"\n            )\n            raise TypeError(msg)\n\n    @override\n    def stream(\n        self,\n        input: Input,\n        config: RunnableConfig | None = None,\n        **kwargs: Any | None,\n    ) -> Iterator[Output]:\n        return self.transform(iter([input]), config, **kwargs)\n\n    async def _atransform(\n        self,\n        chunks: AsyncIterator[Input],\n        run_manager: AsyncCallbackManagerForChainRun,\n        config: RunnableConfig,\n        **kwargs: Any,\n    ) -> AsyncIterator[Output]:\n        final: Input","sourceCodeStart":5408,"sourceCodeEnd":5444,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/runnables/base.py#L5408-L5444","documentation":"`RunnableLambda.transform`/`stream` delegate to `_transform_stream_with_config` only when a sync implementation (`self.func`) exists. For an async-only `RunnableLambda`, sync streaming is impossible, so a `TypeError` is raised telling you to use `astream`. This is the streaming counterpart of the invoke-time sync/async guard.","triggerScenarios":"`RunnableLambda(async_fn).stream(x)` or `.transform(iter([x]))`; a parent `RunnableSequence.stream()` containing an async-only lambda; sync consuming code over an async-built chain.","commonSituations":"Reusing async pipeline definitions in CLI scripts; LangServe/eval harnesses that call `.stream()`; partially migrated codebases mixing sync streaming with async lambdas.","solutions":["Switch to async streaming: `async for chunk in r.astream(x): ...`.","Construct with both paths: `RunnableLambda(sync_fn, afunc=async_fn)`.","Bridge sync: `asyncio.run(collect_async(r.astream(x)))` outside a loop.","Add sync wrappers for any lambda used by sync consumers."],"exampleFix":"# before\nfor chunk in RunnableLambda(async_fn).stream(x):  # TypeError\n    print(chunk)\n\n# after\nasync def main():\n    async for chunk in RunnableLambda(async_fn).astream(x):\n        print(chunk)\nasyncio.run(main())","handlingStrategy":"type-guard","validationCode":"def supports_sync_stream(r) -> bool:\n    return hasattr(r, 'func')","typeGuard":"def can_stream_sync(r) -> bool:\n    return hasattr(r, 'func')","tryCatchPattern":"try:\n    for chunk in r.stream(x):\n        ...\nexcept TypeError as e:\n    if 'astream' in str(e):\n        chunks = asyncio.run(collect(r.astream(x)))\n    else:\n        raise","preventionTips":["Pair every async lambda with a sync func when sync streaming is needed.","Check hasattr(r, 'func') before sync streaming over shared chains.","Keep a sync mirror of async chains for scripts and eval harnesses."],"tags":["runnable","runnable-lambda","streaming","sync-async-mismatch","typeerror"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}