supermemoryai/supermemory · warning

Cannot save memory in sync client from async context

Error message

Cannot save memory in sync client from async context

What it means

This warning is logged when a synchronous OpenAI client wrapped by Supermemory's middleware tries to save memories, but the call happens inside a running asyncio event loop. The middleware detects the classic RuntimeError ('cannot be called from a running event loop') and degrades gracefully by skipping the memory save instead of crashing. Memory persistence for that request is silently lost.

Source

Thrown at packages/openai-sdk-python/src/supermemory_openai/middleware.py:460

                    if self._options.custom_id
                    else None
                )

                # Use asyncio.run() for the memory addition
                try:
                    asyncio.run(
                        add_memory_tool(
                            self._supermemory_client,
                            self._container_tag,
                            content,
                            custom_id,
                            self._logger,
                        )
                    )
                except RuntimeError as e:
                    if "cannot be called from a running event loop" in str(e):
                        # We're in an async context, log warning and skip memory saving
                        self._logger.warn(
                            "Cannot save memory in sync client from async context",
                            {"error": str(e)},
                        )
                    else:
                        raise
                except SupermemoryNetworkError as e:
                    # Network errors are expected, log as warning
                    self._logger.warn("Network error saving memory", {"error": str(e)})
                except (SupermemoryAPIError, SupermemoryMemoryOperationError) as e:
                    # API/memory errors are concerning, log as error
                    self._logger.error("Failed to save memory", {"error": str(e)})
                except Exception as e:
                    # Unexpected errors should be investigated
                    self._logger.error(
                        "Unexpected error saving memory",
                        {"error": str(e), "type": type(e).__name__},
                    )

View on GitHub (pinned to d436792e77)

Solutions

  1. Switch to the async client (AsyncOpenAI + create_with_memory await) anywhere a loop is running
  2. Run the sync call in a genuinely separate thread with no loop, e.g. asyncio.to_thread or a worker, so no event loop is active
  3. If losing memory saves in this path is unacceptable, call the Supermemory memories API directly from async code instead of relying on the sync middleware
  4. Upgrade the SDK; check changelog for improved sync-from-async handling

Example fix

// before
client = SupermemoryOpenAI(OpenAI())
async def handler():
    res = client.chat.completions.create_with_memory(...)  # warns, memory lost

// after
client = SupermemoryOpenAI(AsyncOpenAI())
async def handler():
    res = await client.chat.completions.create_with_memory(...)
Defensive patterns

Strategy: fallback

Validate before calling

import asyncio
try:
    asyncio.get_running_loop()
    in_loop = True
except RuntimeError:
    in_loop = False
# choose sync client only when in_loop is False

Type guard

def has_running_loop() -> bool:
    try:
        asyncio.get_running_loop()
        return True
    except RuntimeError:
        return False

Prevention

When it happens

Trigger: Calling create_with_memory (or chat.completions.create through the sync wrapped client) from inside an async function or a framework with a running loop (Jupyter, FastAPI handler calling blocking SDK code, anyio/asyncio.to_thread offloading back into async). The sync save path uses asyncio.run()/loop.run_until_complete internally, which is illegal while a loop is already running.

Common situations: Using the sync Supermemory-wrapped OpenAI client inside Jupyter notebooks (which always run an event loop), calling it from FastAPI/Starlette async endpoints, or migrating sync code into an async app without switching to AsyncOpenAI. Versions of the middleware that added background memory saving to the sync client exposed this.

Related errors


AI-assisted analysis of supermemoryai/supermemory@d436792e77 (2026-08-28). Data as JSON: /api/errors/8aefc1f14a00b37c. Report an issue: GitHub.