From 808cc53b46932a2305dfb51a272df8382f3eb398 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?W=C3=A4scher=2C=20Andreas?= Date: Wed, 15 Jul 2026 08:16:20 +0200 Subject: [PATCH] Check .Message for null #387 --- src/OllamaSharp/Chat.cs | 8 ++++---- test/ChatTests.cs | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/OllamaSharp/Chat.cs b/src/OllamaSharp/Chat.cs index 2c0f686..a49af65 100644 --- a/src/OllamaSharp/Chat.cs +++ b/src/OllamaSharp/Chat.cs @@ -439,17 +439,17 @@ public async IAsyncEnumerable SendAsAsync(ChatRole role, string message, var messageBuilder = new MessageBuilder(); await foreach (var answer in Client.ChatAsync(request, cancellationToken).ConfigureAwait(false)) { - if (answer is null) + if (answer?.Message is not { } answerMessageChunk) continue; messageBuilder.Append(answer); // yield the message content or call the delegate to handle thinking - var isThinking = (bool?)Think == true && !string.IsNullOrEmpty(answer.Message.Thinking); + var isThinking = (bool?)Think == true && !string.IsNullOrEmpty(answerMessageChunk.Thinking); if (isThinking) - OnThink?.Invoke(this, answer.Message.Thinking!); + OnThink?.Invoke(this, answerMessageChunk.Thinking!); else - yield return answer.Message.Content ?? string.Empty; + yield return answerMessageChunk.Content ?? string.Empty; } if (messageBuilder.HasValue) diff --git a/test/ChatTests.cs b/test/ChatTests.cs index 96d3f99..77238b3 100644 --- a/test/ChatTests.cs +++ b/test/ChatTests.cs @@ -39,6 +39,26 @@ public async Task Sends_Assistant_Answer_To_Streamer() chat.Messages.Last().Content.ShouldBe("Hi human, how are you?"); } + /// + /// Verifies that response chunks without a message are ignored while streaming. + /// + [Test] + public async Task Ignores_Response_Chunks_Without_Message() + { + var ollama = new TestOllamaApiClient(); + ollama.SetExpectedChatResponses( + new ChatResponseStream { Message = CreateMessage(ChatRole.Assistant, "Hi ") }, + new ChatResponseStream { Message = null! }, + new ChatResponseStream { Message = CreateMessage(ChatRole.Assistant, "human") }); + + var chat = new Chat(ollama); + var answer = await chat.SendAsync("henlo", CancellationToken.None).StreamToEndAsync(); + + answer.ShouldBe("Hi human"); + chat.Messages.Last().Role.ShouldBe(ChatRole.Assistant); + chat.Messages.Last().Content.ShouldBe("Hi human"); + } + /// /// Verifies that a tool call generated by the assistant is streamed and recorded correctly. ///