{"record":{"id":"0b9d8cd3309b6c0b","repo":"microsoft/semantic-kernel","slug":"the-thread-could-not-be-deleted-due-to-an-error-re-0b9d8c","errorCode":null,"errorMessage":"The thread could not be deleted due to an error response from the service.","messagePattern":"The thread could not be deleted due to an error response from the service\\.","errorType":"exception","errorClass":"AgentThreadOperationException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/azure_ai/azure_ai_agent.py","lineNumber":315,"sourceCode":"                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.agents.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        if (\n            not new_message.metadata\n            or \"thread_id\" not in new_message.metadata\n            or new_message.metadata[\"thread_id\"] != self.id\n        ):\n            assert self.id is not None  # nosec\n            await AgentThreadActions.create_message(self._client, self.id, new_message)\n\n    async def get_messages(self, sort_order: Literal[\"asc\", \"desc\"] = \"desc\") -> AsyncIterable[ChatMessageContent]:","sourceCodeStart":297,"sourceCodeEnd":333,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/azure_ai/azure_ai_agent.py#L297-L333","documentation":"Raised by AzureAIAgentThread._delete when client.agents.threads.delete raises any exception. The original service error is chained. Commonly the thread was already deleted server-side, or there is an auth/network problem. Surfaced as AgentThreadOperationException.","triggerScenarios":"Deleting a thread that no longer exists (already deleted, or expired); insufficient permissions on the project; network failure; the thread_id refers to a thread in a different project/endpoint; concurrent deletion by another process.","commonSituations":"Cleanup code running twice (idempotency issue); a thread deleted out-of-band (portal/CLI) while the app held a reference; credential rotated between create and delete; transient 5xx.","solutions":["Inspect the chained cause to distinguish 'not found' (treat as success) from real failures.","Make deletion idempotent: swallow 'not found'/404 errors and treat the thread as deleted.","Retry transient 5xx/network errors with backoff; do not retry 403/404.","Avoid deleting the same thread_id from multiple processes without coordination."],"exampleFix":"try:\n    await thread.delete()\nexcept AgentThreadOperationException as e:\n    if _is_not_found(e.__cause__):\n        pass  # already gone, treat as success\n    else:\n        raise","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try:\n    await thread.delete()\nexcept AgentThreadOperationException as e:\n    cause = e.__cause__\n    if _is_not_found(cause):\n        return  # already deleted -> success\n    if _is_transient(cause):\n        await asyncio.sleep(backoff); await thread.delete()\n    else:\n        raise","preventionTips":["Make deletion idempotent by treating 404/not-found as success.","Avoid concurrent deletes of the same thread_id across processes.","Log the chained cause to distinguish auth from not-found from transient."],"tags":["azure-ai","thread","lifecycle","service-error","idempotency"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}