Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/OllamaSharp/Chat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -439,17 +439,17 @@ public async IAsyncEnumerable<string> 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)
Expand Down
20 changes: 20 additions & 0 deletions test/ChatTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ public async Task Sends_Assistant_Answer_To_Streamer()
chat.Messages.Last().Content.ShouldBe("Hi human, how are you?");
}

/// <summary>
/// Verifies that response chunks without a message are ignored while streaming.
/// </summary>
[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");
}

/// <summary>
/// Verifies that a tool call generated by the assistant is streamed and recorded correctly.
/// </summary>
Expand Down
Loading