|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System.Text; |
| 4 | +using Microsoft.SemanticKernel; |
| 5 | +using Microsoft.SemanticKernel.ChatCompletion; |
| 6 | +using Microsoft.SemanticKernel.Connectors.Ollama; |
| 7 | + |
| 8 | +namespace ChatCompletion; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// These examples demonstrate the ways different content types are streamed by Ollama via the chat completion service. |
| 12 | +/// </summary> |
| 13 | +public class Ollama_ChatCompletionStreaming(ITestOutputHelper output) : BaseTest(output) |
| 14 | +{ |
| 15 | + /// <summary> |
| 16 | + /// This example demonstrates chat completion streaming using Ollama. |
| 17 | + /// </summary> |
| 18 | + [Fact] |
| 19 | + public Task StreamChatAsync() |
| 20 | + { |
| 21 | + Assert.NotNull(TestConfiguration.Ollama.ModelId); |
| 22 | + |
| 23 | + Console.WriteLine("======== Ollama - Chat Completion Streaming ========"); |
| 24 | + |
| 25 | + var chatService = new OllamaChatCompletionService( |
| 26 | + endpoint: new Uri(TestConfiguration.Ollama.Endpoint), |
| 27 | + modelId: TestConfiguration.Ollama.ModelId); |
| 28 | + |
| 29 | + return this.StartStreamingChatAsync(chatService); |
| 30 | + } |
| 31 | + |
| 32 | + [Fact] |
| 33 | + public async Task StreamChatPromptAsync() |
| 34 | + { |
| 35 | + Assert.NotNull(TestConfiguration.Ollama.ModelId); |
| 36 | + |
| 37 | + StringBuilder chatPrompt = new(""" |
| 38 | + <message role="system">You are a librarian, expert about books</message> |
| 39 | + <message role="user">Hi, I'm looking for book suggestions</message> |
| 40 | + """); |
| 41 | + |
| 42 | + var kernel = Kernel.CreateBuilder() |
| 43 | + .AddOllamaChatCompletion( |
| 44 | + endpoint: new Uri(TestConfiguration.Ollama.Endpoint), |
| 45 | + modelId: TestConfiguration.Ollama.ModelId) |
| 46 | + .Build(); |
| 47 | + |
| 48 | + var reply = await StreamMessageOutputFromKernelAsync(kernel, chatPrompt.ToString()); |
| 49 | + |
| 50 | + chatPrompt.AppendLine($"<message role=\"assistant\"><![CDATA[{reply}]]></message>"); |
| 51 | + chatPrompt.AppendLine("<message role=\"user\">I love history and philosophy, I'd like to learn something new about Greece, any suggestion</message>"); |
| 52 | + |
| 53 | + reply = await StreamMessageOutputFromKernelAsync(kernel, chatPrompt.ToString()); |
| 54 | + |
| 55 | + Console.WriteLine(reply); |
| 56 | + } |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// This example demonstrates how the chat completion service streams text content. |
| 60 | + /// It shows how to access the response update via StreamingChatMessageContent.Content property |
| 61 | + /// and alternatively via the StreamingChatMessageContent.Items property. |
| 62 | + /// </summary> |
| 63 | + [Fact] |
| 64 | + public async Task StreamTextFromChatAsync() |
| 65 | + { |
| 66 | + Assert.NotNull(TestConfiguration.Ollama.ModelId); |
| 67 | + |
| 68 | + Console.WriteLine("======== Stream Text from Chat Content ========"); |
| 69 | + |
| 70 | + // Create chat completion service |
| 71 | + var chatService = new OllamaChatCompletionService( |
| 72 | + endpoint: new Uri(TestConfiguration.Ollama.Endpoint), |
| 73 | + modelId: TestConfiguration.Ollama.ModelId); |
| 74 | + |
| 75 | + // Create chat history with initial system and user messages |
| 76 | + ChatHistory chatHistory = new("You are a librarian, an expert on books."); |
| 77 | + chatHistory.AddUserMessage("Hi, I'm looking for book suggestions."); |
| 78 | + chatHistory.AddUserMessage("I love history and philosophy. I'd like to learn something new about Greece, any suggestion?"); |
| 79 | + |
| 80 | + // Start streaming chat based on the chat history |
| 81 | + await foreach (StreamingChatMessageContent chatUpdate in chatService.GetStreamingChatMessageContentsAsync(chatHistory)) |
| 82 | + { |
| 83 | + // Access the response update via StreamingChatMessageContent.Content property |
| 84 | + Console.Write(chatUpdate.Content); |
| 85 | + |
| 86 | + // Alternatively, the response update can be accessed via the StreamingChatMessageContent.Items property |
| 87 | + Console.Write(chatUpdate.Items.OfType<StreamingTextContent>().FirstOrDefault()); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + private async Task StartStreamingChatAsync(IChatCompletionService chatCompletionService) |
| 92 | + { |
| 93 | + Console.WriteLine("Chat content:"); |
| 94 | + Console.WriteLine("------------------------"); |
| 95 | + |
| 96 | + var chatHistory = new ChatHistory("You are a librarian, expert about books"); |
| 97 | + this.OutputLastMessage(chatHistory); |
| 98 | + |
| 99 | + // First user message |
| 100 | + chatHistory.AddUserMessage("Hi, I'm looking for book suggestions"); |
| 101 | + this.OutputLastMessage(chatHistory); |
| 102 | + |
| 103 | + // First assistant message |
| 104 | + await StreamMessageOutputAsync(chatCompletionService, chatHistory, AuthorRole.Assistant); |
| 105 | + |
| 106 | + // Second user message |
| 107 | + chatHistory.AddUserMessage("I love history and philosophy, I'd like to learn something new about Greece, any suggestion?"); |
| 108 | + this.OutputLastMessage(chatHistory); |
| 109 | + |
| 110 | + // Second assistant message |
| 111 | + await StreamMessageOutputAsync(chatCompletionService, chatHistory, AuthorRole.Assistant); |
| 112 | + } |
| 113 | + |
| 114 | + private async Task StreamMessageOutputAsync(IChatCompletionService chatCompletionService, ChatHistory chatHistory, AuthorRole authorRole) |
| 115 | + { |
| 116 | + bool roleWritten = false; |
| 117 | + string fullMessage = string.Empty; |
| 118 | + |
| 119 | + await foreach (var chatUpdate in chatCompletionService.GetStreamingChatMessageContentsAsync(chatHistory)) |
| 120 | + { |
| 121 | + if (!roleWritten && chatUpdate.Role.HasValue) |
| 122 | + { |
| 123 | + Console.Write($"{chatUpdate.Role.Value}: {chatUpdate.Content}"); |
| 124 | + roleWritten = true; |
| 125 | + } |
| 126 | + |
| 127 | + if (chatUpdate.Content is { Length: > 0 }) |
| 128 | + { |
| 129 | + fullMessage += chatUpdate.Content; |
| 130 | + Console.Write(chatUpdate.Content); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + Console.WriteLine("\n------------------------"); |
| 135 | + chatHistory.AddMessage(authorRole, fullMessage); |
| 136 | + } |
| 137 | + |
| 138 | + private async Task<string> StreamMessageOutputFromKernelAsync(Kernel kernel, string prompt) |
| 139 | + { |
| 140 | + bool roleWritten = false; |
| 141 | + string fullMessage = string.Empty; |
| 142 | + |
| 143 | + await foreach (var chatUpdate in kernel.InvokePromptStreamingAsync<StreamingChatMessageContent>(prompt)) |
| 144 | + { |
| 145 | + if (!roleWritten && chatUpdate.Role.HasValue) |
| 146 | + { |
| 147 | + Console.Write($"{chatUpdate.Role.Value}: {chatUpdate.Content}"); |
| 148 | + roleWritten = true; |
| 149 | + } |
| 150 | + |
| 151 | + if (chatUpdate.Content is { Length: > 0 }) |
| 152 | + { |
| 153 | + fullMessage += chatUpdate.Content; |
| 154 | + Console.Write(chatUpdate.Content); |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + Console.WriteLine("\n------------------------"); |
| 159 | + return fullMessage; |
| 160 | + } |
| 161 | +} |
0 commit comments