{"record":{"id":"268f07c513cb2a9a","repo":"microsoft/semantic-kernel","slug":"the-message-could-not-be-added-to-the-thread-due-t-268f07","errorCode":null,"errorMessage":"The message could not be added to the thread due to an error response from the service.","messagePattern":"The message could not be added to the thread due to an error response from the service\\.","errorType":"exception","errorClass":"AgentThreadOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Agents/OpenAI/OpenAIAssistantAgentThread.cs","lineNumber":166,"sourceCode":"            throw new AgentThreadOperationException(ErrorMessage, ex);\n        }\n    }\n\n    /// <inheritdoc />\n    protected override async Task OnNewMessageInternalAsync(ChatMessageContent newMessage, CancellationToken cancellationToken = default)\n    {\n        const string ErrorMessage = \"The message could not be added to the thread due to an error response from the service.\";\n\n        // If the message was generated by this agent, it is already in the thread and we shouldn't add it again.\n        if (newMessage.Metadata == null || !newMessage.Metadata.TryGetValue(\"ThreadId\", out var messageThreadId) || !string.Equals(messageThreadId, this.Id))\n        {\n            try\n            {\n                await AssistantThreadActions.CreateMessageAsync(this._client, this.Id!, newMessage, cancellationToken).ConfigureAwait(false);\n            }\n            catch (ClientResultException ex)\n            {\n                throw new AgentThreadOperationException(ErrorMessage, ex);\n            }\n            catch (AggregateException ex)\n            {\n                throw new AgentThreadOperationException(ErrorMessage, ex);\n            }\n        }\n    }\n\n    /// <summary>\n    /// Asynchronously retrieves all messages in the thread.\n    /// </summary>\n    /// <param name=\"sortOrder\">The order to return messages in.</param>\n    /// <param name=\"cancellationToken\">The <see cref=\"CancellationToken\"/> to monitor for cancellation requests. The default is <see cref=\"CancellationToken.None\"/>.</param>\n    /// <returns>The messages in the thread.</returns>\n    /// <exception cref=\"InvalidOperationException\">The thread has been deleted.</exception>\n    [Experimental(\"SKEXP0110\")]\n    public async IAsyncEnumerable<ChatMessageContent> GetMessagesAsync(MessageCollectionOrder? sortOrder = default, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n    {","sourceCodeStart":148,"sourceCodeEnd":184,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/dotnet/src/Agents/OpenAI/OpenAIAssistantAgentThread.cs#L148-L184","documentation":"OnNewMessageInternalAsync wraps AssistantThreadActions.CreateMessageAsync; a ClientResultException or AggregateException from adding a message is rethrown as AgentThreadOperationException. (The message is only added when it is not already native to this thread.)","triggerScenarios":"Appending a chat message to a server-backed thread when the service rejects it: auth failure, invalid message content, rate limit, or a missing/inconsistent thread id.","commonSituations":"Adding an externally created message to the thread; expired credentials mid-conversation; malformed message items; quota/rate limits.","solutions":["Catch AgentThreadOperationException and inspect the inner ClientResultException/AggregateException for status and message.","Validate the message content/role before adding it.","Confirm the thread id is current and the thread still exists.","Retry transient failures (429/5xx) with backoff."],"exampleFix":"// before\nawait thread.AddMessageAsync(message);\n// after\ntry { await thread.AddMessageAsync(message); }\ncatch (AgentThreadOperationException ex) {\n    logger.LogError(ex, \"Failed to add message to thread\");\n    if (ex.InnerException is ClientResultException cre) logger.LogError(cre, \"HTTP {Status}\", cre.Status);\n}","handlingStrategy":"try-catch","validationCode":"if (newMessage.Metadata != null && newMessage.Metadata.TryGetValue(\"ThreadId\", out var id) && string.Equals(id, thread.Id))\n    return; // already native to this thread, no add needed","typeGuard":null,"tryCatchPattern":"try { await thread.AddMessageAsync(message); }\ncatch (AgentThreadOperationException ex) {\n    logger.LogError(ex, \"Add message failed\");\n    if (ex.InnerException is ClientResultException cre && (cre.Status == 429 || cre.Status >= 500))\n        await RetryAsync(() => thread.AddMessageAsync(message));\n}","preventionTips":["Validate message content/role before adding it.","Confirm the thread id is current and the thread exists.","Retry transient (429/5xx) add-message failures with backoff."],"tags":["openai","agent-thread","network","service-error"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}