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