{"record":{"id":"5798b262187daa84","repo":"microsoft/autogen","slug":"failed-to-initialize-chromadb","errorCode":null,"errorMessage":"Failed to initialize ChromaDB","messagePattern":"Failed to initialize ChromaDB","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-ext/src/autogen_ext/memory/chromadb/_chromadb.py","lineNumber":338,"sourceCode":"        query_text = last_message.content if isinstance(last_message.content, str) else str(last_message)\n\n        # Query memory and get results\n        query_results = await self.query(query_text)\n\n        if query_results.results:\n            # Format results for context\n            memory_strings = [f\"{i}. {str(memory.content)}\" for i, memory in enumerate(query_results.results, 1)]\n            memory_context = \"\\nRelevant memory content:\\n\" + \"\\n\".join(memory_strings)\n\n            # Add to context\n            await model_context.add_message(SystemMessage(content=memory_context))\n\n        return UpdateContextResult(memories=query_results)\n\n    async def add(self, content: MemoryContent, cancellation_token: CancellationToken | None = None) -> None:\n        self._ensure_initialized()\n        if self._collection is None:\n            raise RuntimeError(\"Failed to initialize ChromaDB\")\n\n        try:\n            # Extract text from content\n            text = self._extract_text(content)\n\n            # Use metadata directly from content\n            metadata_dict = content.metadata or {}\n            metadata_dict[\"mime_type\"] = str(content.mime_type)\n\n            # Add to ChromaDB\n            self._collection.add(documents=[text], metadatas=[metadata_dict], ids=[str(uuid.uuid4())])\n\n        except Exception as e:\n            logger.error(f\"Failed to add content to ChromaDB: {e}\")\n            raise\n\n    async def query(\n        self,","sourceCodeStart":320,"sourceCodeEnd":356,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/memory/chromadb/_chromadb.py#L320-L356","documentation":"Raised by ChromaDBVectorMemory.add when the internal _collection is still None after _ensure_initialized(). It signals that lazy initialization either never ran or failed without raising, so no collection handle exists to write to. In practice it means the memory was closed, reset, or failed to connect to the ChromaDB client.","triggerScenarios":"Calling add() after close() (which sets _collection = None); calling add() after reset(); _ensure_initialized failing silently (e.g. PersistentClient path with a bad directory or client error swallowed elsewhere); calling add() on a memory instance deserialized/reconstructed without initialization.","commonSituations":"Reusing a memory object across agent runs after an explicit close in cleanup code; telemetry/shutdown hooks closing memory while background tasks still add; PersistentClient failing due to permissions or a locked SQLite directory so the collection is never created.","solutions":["Do not call add() after close()/reset(); create a fresh ChromaDBVectorMemory instance for the next session.","Ensure construction arguments (client_type, path, collection settings) are valid so first use initializes the collection successfully.","If a background task adds memories, await its cancellation and join before closing the memory in shutdown."],"exampleFix":"# before\nawait memory.close()\nawait memory.add(content)  # RuntimeError\n\n# after\nawait memory.close()\nmemory = ChromaDBVectorMemory(config=ChromaDBVectorMemoryConfig(collection_name='memos'))\nawait memory.add(content)","handlingStrategy":"validation","validationCode":"def memory_ready(memory) -> bool:\n    return getattr(memory, '_collection', None) is not None or memory._client is not None and False","typeGuard":null,"tryCatchPattern":"try:\n    await memory.add(content)\nexcept RuntimeError as e:\n    if 'Failed to initialize' in str(e):\n        memory = await rebuild_memory()  # fresh instance, retry once\n        await memory.add(content)\n    else:\n        raise","preventionTips":["Never add() after close()/reset(); create a new memory instance per session","Track a closed flag on wrappers and raise a clear app-level error first","Join/cancel background writers before closing memory in shutdown"],"tags":["chromadb","lifecycle","memory","runtime-state"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}