{"record":{"id":"00aec15e15a1f25b","repo":"langchain-ai/langchain","slug":"cannot-invoke-a-coroutine-function-synchronously-u","errorCode":null,"errorMessage":"Cannot invoke a coroutine function synchronously.Use `ainvoke` instead.","messagePattern":"Cannot invoke a coroutine function synchronously\\.Use `ainvoke` instead\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/runnables/base.py","lineNumber":5318,"sourceCode":"            config: The config to use.\n            **kwargs: Additional keyword arguments.\n\n        Returns:\n            The output of this `Runnable`.\n\n        Raises:\n            TypeError: If the `Runnable` is a coroutine function.\n\n        \"\"\"\n        if hasattr(self, \"func\"):\n            return self._call_with_config(\n                self._invoke,\n                input,\n                ensure_config(config),\n                **kwargs,\n            )\n        msg = \"Cannot invoke a coroutine function synchronously.Use `ainvoke` instead.\"\n        raise TypeError(msg)\n\n    @override\n    async def ainvoke(\n        self,\n        input: Input,\n        config: RunnableConfig | None = None,\n        **kwargs: Any | None,\n    ) -> Output:\n        \"\"\"Invoke this `Runnable` asynchronously.\n\n        Args:\n            input: The input to this `Runnable`.\n            config: The config to use.\n            **kwargs: Additional keyword arguments.\n\n        Returns:\n            The output of this `Runnable`.\n","sourceCodeStart":5300,"sourceCodeEnd":5336,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/runnables/base.py#L5300-L5336","documentation":"`RunnableLambda.invoke` only works when the object was constructed with a sync callable (stored as `self.func`). If it was created from a coroutine function only (`RunnableLambda(async_fn)` or `func=..., afunc=...` where the sync path is absent), there is no synchronous implementation and calling `.invoke()` raises `TypeError` directing you to `ainvoke`. Coroutine functions cannot be executed from sync code without an event loop.","triggerScenarios":"`r = RunnableLambda(async_fn)` then `r.invoke(x)`; a chain containing an async-only lambda invoked synchronously (`chain.invoke(x)`); sync test code exercising an async-built pipeline.","commonSituations":"Sharing runnables between async servers and sync scripts; tutorials written async being adapted into sync notebooks; forgetting a `func` when both `func`/`afunc` were planned.","solutions":["Use `await r.ainvoke(x)` in async contexts.","Provide a sync implementation too: `RunnableLambda(sync_fn, afunc=async_fn)`.","Bridge in sync code: `asyncio.run(r.ainvoke(x))` (only when no loop is running).","Inside a running loop, offload via `asyncio.run_coroutine_threadsafe` from another thread."],"exampleFix":"# before\nr = RunnableLambda(async_fetch)  # async only\nresult = r.invoke('doc')  # TypeError\n\n# after\nresult = asyncio.run(r.ainvoke('doc'))\n# or supply both:\nr = RunnableLambda(sync_fetch, afunc=async_fetch)\nresult = r.invoke('doc')","handlingStrategy":"type-guard","validationCode":"def supports_sync_invoke(r) -> bool:\n    return hasattr(r, 'func')","typeGuard":"def is_sync_runnable_lambda(r) -> bool:\n    return hasattr(r, 'func')","tryCatchPattern":"try:\n    out = r.invoke(x)\nexcept TypeError as e:\n    if 'ainvoke' in str(e):\n        out = asyncio.run(r.ainvoke(x))\n    else:\n        raise","preventionTips":["Provide both func and afunc for runnables used in both execution modes.","Standardize entry points: sync callers get sync-built chains.","Use asyncio.run only when no event loop is already running."],"tags":["runnable","runnable-lambda","sync-async-mismatch","typeerror","asyncio"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}