{"record":{"id":"5dc84071eb27bf0e","repo":"microsoft/semantic-kernel","slug":"the-thread-cannot-be-deleted-because-it-has-not-be-5dc840","errorCode":null,"errorMessage":"The thread cannot be deleted because it has not been created yet.","messagePattern":"The thread cannot be deleted because it has not been created yet\\.","errorType":"exception","errorClass":"AgentThreadOperationException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/open_ai/openai_assistant_agent.py","lineNumber":186,"sourceCode":"    async def _create(self) -> str:\n        \"\"\"Starts the thread and returns its ID.\"\"\"\n        try:\n            response = await self._client.beta.threads.create(\n                messages=self._messages,\n                metadata=self._metadata,\n                tool_resources=self._tool_resources,\n            )\n        except Exception as ex:\n            raise AgentThreadOperationException(\n                \"The thread could not be created due to an error response from the service.\"\n            ) from ex\n        return response.id\n\n    @override\n    async def _delete(self) -> None:\n        \"\"\"Ends the current thread.\"\"\"\n        if self._id is None:\n            raise AgentThreadOperationException(\"The thread cannot be deleted because it has not been created yet.\")\n        try:\n            await self._client.beta.threads.delete(self._id)\n        except Exception as ex:\n            raise AgentThreadOperationException(\n                \"The thread could not be deleted due to an error response from the service.\"\n            ) from ex\n\n    @override\n    async def _on_new_message(self, new_message: str | ChatMessageContent) -> None:\n        \"\"\"Called when a new message has been contributed to the chat.\"\"\"\n        if isinstance(new_message, str):\n            new_message = ChatMessageContent(role=AuthorRole.USER, content=new_message)\n\n        # Only add the message to the thread if it's not already there\n        if (\n            not new_message.metadata\n            or \"thread_id\" not in new_message.metadata\n            or new_message.metadata[\"thread_id\"] != self._id","sourceCodeStart":168,"sourceCodeEnd":204,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/open_ai/openai_assistant_agent.py#L168-L204","documentation":"Raised as AgentThreadOperationException by AssistantAgentThread._delete when self._id is None, meaning the thread was never created (create() not called or failed) before delete was invoked. The SDK guards against sending a delete request with no thread id.","triggerScenarios":"Calling thread.delete() before thread.create() has successfully set an id, or after a prior create() failed so _id remained None.","commonSituations":"Forgetting to create the thread in a flow that only deletes; an earlier create() raised and the code continued to delete; deleting in a cleanup/finally block without checking creation succeeded.","solutions":["Ensure create() succeeds before calling delete(); only delete when thread.id is not None.","In cleanup blocks, guard: if thread.id is not None: await thread.delete().","Handle create() failures so delete is not reached with no id."],"exampleFix":"# before\nawait thread.create()  # may have failed\nawait thread.delete()  # _id None -> error\n# after\nawait thread.create()\nif thread.id is not None:\n    await thread.delete()","handlingStrategy":"validation","validationCode":"# only delete when the thread actually exists\nif thread.id is not None:\n    await thread.delete()\nelse:\n    logging.warning(\"Skipping delete: thread was never created.\")","typeGuard":"def thread_is_created(thread) -> bool:\n    return getattr(thread, \"_id\", None) is not None","tryCatchPattern":null,"preventionTips":["Guard delete() with a check on thread.id.","In finally/cleanup blocks, only delete when creation succeeded.","Handle create() failures so delete is not reached."],"tags":["openai","semantic-kernel","agents","threads","validation","lifecycle"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}