microsoft/semantic-kernel · error · AgentThreadOperationException

The message could not be added to the thread due to an error

Error message

The message could not be added to the thread due to an error response from the service.

What it means

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.)

Source

Thrown at dotnet/src/Agents/OpenAI/OpenAIAssistantAgentThread.cs:166

            throw new AgentThreadOperationException(ErrorMessage, ex);
        }
    }

    /// <inheritdoc />
    protected override async Task OnNewMessageInternalAsync(ChatMessageContent newMessage, CancellationToken cancellationToken = default)
    {
        const string ErrorMessage = "The message could not be added to the thread due to an error response from the service.";

        // If the message was generated by this agent, it is already in the thread and we shouldn't add it again.
        if (newMessage.Metadata == null || !newMessage.Metadata.TryGetValue("ThreadId", out var messageThreadId) || !string.Equals(messageThreadId, this.Id))
        {
            try
            {
                await AssistantThreadActions.CreateMessageAsync(this._client, this.Id!, newMessage, cancellationToken).ConfigureAwait(false);
            }
            catch (ClientResultException ex)
            {
                throw new AgentThreadOperationException(ErrorMessage, ex);
            }
            catch (AggregateException ex)
            {
                throw new AgentThreadOperationException(ErrorMessage, ex);
            }
        }
    }

    /// <summary>
    /// Asynchronously retrieves all messages in the thread.
    /// </summary>
    /// <param name="sortOrder">The order to return messages in.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
    /// <returns>The messages in the thread.</returns>
    /// <exception cref="InvalidOperationException">The thread has been deleted.</exception>
    [Experimental("SKEXP0110")]
    public async IAsyncEnumerable<ChatMessageContent> GetMessagesAsync(MessageCollectionOrder? sortOrder = default, [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Catch AgentThreadOperationException and inspect the inner ClientResultException/AggregateException for status and message.
  2. Validate the message content/role before adding it.
  3. Confirm the thread id is current and the thread still exists.
  4. Retry transient failures (429/5xx) with backoff.

Example fix

// before
await thread.AddMessageAsync(message);
// after
try { await thread.AddMessageAsync(message); }
catch (AgentThreadOperationException ex) {
    logger.LogError(ex, "Failed to add message to thread");
    if (ex.InnerException is ClientResultException cre) logger.LogError(cre, "HTTP {Status}", cre.Status);
}
Defensive patterns

Strategy: try-catch

Validate before calling

if (newMessage.Metadata != null && newMessage.Metadata.TryGetValue("ThreadId", out var id) && string.Equals(id, thread.Id))
    return; // already native to this thread, no add needed

Try / catch

try { await thread.AddMessageAsync(message); }
catch (AgentThreadOperationException ex) {
    logger.LogError(ex, "Add message failed");
    if (ex.InnerException is ClientResultException cre && (cre.Status == 429 || cre.Status >= 500))
        await RetryAsync(() => thread.AddMessageAsync(message));
}

Prevention

When it happens

Trigger: 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.

Common situations: Adding an externally created message to the thread; expired credentials mid-conversation; malformed message items; quota/rate limits.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/268f07c513cb2a9a. Report an issue: GitHub.