{"record":{"id":"8b74dd3ba4d9a2ef","repo":"microsoft/semantic-kernel","slug":"cannot-retrieve-chat-history-since-the-thread-has-8b74dd","errorCode":null,"errorMessage":"Cannot retrieve chat history, since the thread has been deleted.","messagePattern":"Cannot retrieve chat history, since the thread has been deleted\\.","errorType":"exception","errorClass":"AgentThreadOperationException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/chat_completion/chat_completion_agent.py","lineNumber":101,"sourceCode":"        \"\"\"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            self._chat_history.add_message(new_message)\n\n    async def get_messages(self) -> AsyncIterable[ChatMessageContent]:\n        \"\"\"Retrieve the current chat history.\n\n        Returns:\n            An async iterable of ChatMessageContent.\n        \"\"\"\n        if self._is_deleted:\n            raise AgentThreadOperationException(\"Cannot retrieve chat history, since the thread has been deleted.\")\n        if self._id is None:\n            await self.create()\n        for message in self._chat_history.messages:\n            yield message\n\n    async def reduce(self) -> ChatHistory | None:\n        \"\"\"Reduce the chat history to a smaller size.\"\"\"\n        if self._id is None:\n            raise AgentThreadOperationException(\"Cannot reduce chat history, since the thread is not currently active.\")\n        if not isinstance(self._chat_history, ChatHistoryReducer):\n            return None\n        return await self._chat_history.reduce()\n\n\n@register_agent_type(\"chat_completion_agent\")\nclass ChatCompletionAgent(DeclarativeSpecMixin, Agent):\n    \"\"\"A Chat Completion Agent based on ChatCompletionClientBase.\"\"\"\n","sourceCodeStart":83,"sourceCodeEnd":119,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/chat_completion/chat_completion_agent.py#L83-L119","documentation":"Raised by the chat-completion AgentThread.get_messages (an AgentThreadOperationException) when self._is_deleted is true. Once the thread is deleted, the in-memory chat history is no longer accessible through this thread handle, so retrieval is blocked.","triggerScenarios":"Calling thread.get_messages() after thread.delete() has been called on the same AgentThread instance; reusing a thread handle whose lifecycle has ended.","commonSituations":"Teardown then a delayed/raced read; holding a thread reference across a delete boundary; cleanup logic that deletes then a finally-block tries to log messages.","solutions":["Do not call get_messages after delete; obtain a fresh thread for a new conversation.","Track deletion state in your code and skip reads once the thread is deleted.","Move any history inspection before the delete call.","If you need history after deletion, persist it before deleting."],"exampleFix":"// before\nawait thread.delete()\nmsgs = [m async for m in thread.get_messages()]  # raises\n// after\nmsgs = [m async for m in thread.get_messages()]  # read first\nawait thread.delete()","handlingStrategy":"validation","validationCode":"if thread._is_deleted:\n    raise RuntimeError('Thread already deleted; cannot read messages')\nmsgs = [m async for m in thread.get_messages()]","typeGuard":"def thread_is_active(thread) -> bool:\n    return not getattr(thread, '_is_deleted', False)","tryCatchPattern":"from semantic_kernel.exceptions.agent_exceptions import AgentThreadOperationException\ntry:\n    msgs = [m async for m in thread.get_messages()]\nexcept AgentThreadOperationException as e:\n    if 'has been deleted' in str(e): msgs = []\n    else: raise","preventionTips":["Read history before delete","Track deletion state in your code and skip post-delete reads"],"tags":["chat-completion","thread-lifecycle","agent-thread","validation"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}