Files
semantic-kernel/samples/dotnet/kernel-syntax-examples/Example37_MultiStreamingCompletion.cs
T
af03e00a79 Feature serviceregistry (#993)
### Motivation, Context and Description

This PR introduces several changes aimed to simplify the kernel and
enhancing its extensibility for AI services management. The changes
include the following:

1. Kernel simplification and extensibility: The code responsible for AI
services management, such as registration and resolution, has been moved
out of the Kernel and KernelConfig classes into a new class called
AIServiceProvider. This restructuring promotes the principle of Single
Responsibility, ensuring that each class has a clear and focused
purpose.

2. Hosting apps customization: With the introduction of the
AIServiceProvider, hosting applications now have the flexibility to
provide their own implementation of the provider if needed. This
promotes extensibility, allowing the hosting apps to tailor the AI
service management according to their specific requirements.

3. AI services registration improvements: A new method called
WithAiService has been added, which enables the registration of any new
AI service that is not currently supported.

4. Improved kernel builder interface: The Add* methods for AI services
registration have been moved from the KernelConfig class to the
KernelBuilder. This change aligns the interface with other KernelBilder
methods, such as WithLogger and WithMemory, creating a more cohesive and
intuitive kernel builder interface.

---------

Co-authored-by: Shawn Callegari <[email protected]>
Co-authored-by: Lee Miller <[email protected]>
2023-05-22 15:21:48 -07:00

129 lines
4.1 KiB
C#

// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.AI.TextCompletion;
using RepoUtils;
/**
* The following example shows how to use Semantic Kernel with Multiple Results Text Completion as streaming
*/
// ReSharper disable once InconsistentNaming
public static class Example37_MultiStreamingCompletion
{
private static readonly object s_lockObject = new();
public static async Task RunAsync()
{
await AzureOpenAIMultiTextCompletionStreamAsync();
await OpenAITextCompletionStreamAsync();
}
private static async Task AzureOpenAIMultiTextCompletionStreamAsync()
{
Console.WriteLine("======== Azure OpenAI - Multiple Text Completion - Raw Streaming ========");
IKernel kernel = new KernelBuilder()
.WithAzureTextCompletionService(
Env.Var("AZURE_OPENAI_DEPLOYMENT_NAME"),
Env.Var("AZURE_OPENAI_ENDPOINT"),
Env.Var("AZURE_OPENAI_KEY"))
.WithLogger(ConsoleLogger.Log).Build();
ITextCompletion textCompletion = kernel.GetService<ITextCompletion>();
await TextCompletionStreamAsync(textCompletion);
}
private static async Task OpenAITextCompletionStreamAsync()
{
Console.WriteLine("======== Open AI - Multiple Text Completion - Raw Streaming ========");
IKernel kernel = new KernelBuilder()
.WithOpenAITextCompletionService("text-davinci-003", Env.Var("OPENAI_API_KEY"), serviceId: "text-davinci-003")
.WithLogger(ConsoleLogger.Log).Build();
ITextCompletion textCompletion = kernel.GetService<ITextCompletion>();
await TextCompletionStreamAsync(textCompletion);
}
private static async Task TextCompletionStreamAsync(ITextCompletion textCompletion)
{
var requestSettings = new CompleteRequestSettings()
{
MaxTokens = 200,
FrequencyPenalty = 0,
PresencePenalty = 0,
Temperature = 1,
TopP = 0.5,
ResultsPerPrompt = 3
};
var prompt = "Write one paragraph why AI is awesome";
var consoleLinesPerResult = 12;
PrepareDisplay();
List<Task> resultTasks = new();
int currentResult = 0;
await foreach (var completionResult in textCompletion.GetStreamingCompletionsAsync(prompt, requestSettings))
{
resultTasks.Add(ProcessStreamAsyncEnumerableAsync(completionResult, currentResult++, consoleLinesPerResult));
}
Console.WriteLine();
await Task.WhenAll(resultTasks.ToArray());
/*
int position = 0;
await foreach (ITextCompletionStreamingResult completionResult in textCompletion.CompleteMultiStreamAsync(prompt, requestSettings))
{
string fullMessage = string.Empty;
await foreach (string message in completionResult.GetCompletionStreamingAsync())
{
fullMessage += message;
Console.SetCursorPosition(0, (position * consoleLinesPerResult));
Console.Write(fullMessage);
}
position++;
}*/
Console.SetCursorPosition(0, requestSettings.ResultsPerPrompt * consoleLinesPerResult);
Console.WriteLine();
}
private static async Task ProcessStreamAsyncEnumerableAsync(ITextCompletionStreamingResult result, int resultNumber, int linesPerResult)
{
var fullSentence = string.Empty;
await foreach (var word in result.GetCompletionStreamingAsync())
{
fullSentence += word;
lock (s_lockObject)
{
Console.SetCursorPosition(0, (resultNumber * linesPerResult));
Console.Write(fullSentence);
}
}
}
/// <summary>
/// Break enough lines as the current console window size to display the results
/// </summary>
private static void PrepareDisplay()
{
for (int i = 0; i < Console.WindowHeight - 2; i++)
{
Console.WriteLine();
}
}
}