|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Examples; |
| 9 | +using Kusto.Cloud.Platform.Utils; |
| 10 | +using Microsoft.SemanticKernel; |
| 11 | +using Microsoft.SemanticKernel.ChatCompletion; |
| 12 | +using Microsoft.SemanticKernel.Connectors.OpenAI; |
| 13 | +using Microsoft.SemanticKernel.Experimental.Agents; |
| 14 | +using Xunit; |
| 15 | +using Xunit.Abstractions; |
| 16 | + |
| 17 | +public class Example79_ChatCompletionAgent : BaseTest |
| 18 | +{ |
| 19 | + /// <summary> |
| 20 | + /// This example demonstrates a chat with the chat completion agent that utilizes the SK ChatCompletion API to communicate with LLM. |
| 21 | + /// </summary> |
| 22 | + [Fact] |
| 23 | + public async Task ChatWithAgentAsync() |
| 24 | + { |
| 25 | + var kernel = Kernel.CreateBuilder() |
| 26 | + .AddAzureOpenAIChatCompletion( |
| 27 | + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, |
| 28 | + endpoint: TestConfiguration.AzureOpenAI.Endpoint, |
| 29 | + apiKey: TestConfiguration.AzureOpenAI.ApiKey, |
| 30 | + modelId: TestConfiguration.AzureOpenAI.ChatModelId) |
| 31 | + .Build(); |
| 32 | + |
| 33 | + var agent = new ChatCompletionAgent( |
| 34 | + kernel, |
| 35 | + instructions: "You act as a professional financial adviser. However, clients may not know the terminology, so please provide a simple explanation.", |
| 36 | + new OpenAIPromptExecutionSettings |
| 37 | + { |
| 38 | + MaxTokens = 500, |
| 39 | + Temperature = 0.7, |
| 40 | + TopP = 1.0, |
| 41 | + PresencePenalty = 0.0, |
| 42 | + FrequencyPenalty = 0.0, |
| 43 | + } |
| 44 | + ); |
| 45 | + |
| 46 | + var prompt = PrintPrompt("I need help with my investment portfolio. Please guide me."); |
| 47 | + PrintConversation(await agent.InvokeAsync(new[] { new ChatMessageContent(AuthorRole.User, prompt) })); |
| 48 | + } |
| 49 | + |
| 50 | + /// <summary> |
| 51 | + /// This example demonstrates a round-robin chat between two chat completion agents using the TurnBasedChat collaboration experience. |
| 52 | + /// </summary> |
| 53 | + [Fact] |
| 54 | + public async Task TurnBasedAgentsChatAsync() |
| 55 | + { |
| 56 | + var kernel = Kernel.CreateBuilder() |
| 57 | + .AddAzureOpenAIChatCompletion( |
| 58 | + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, |
| 59 | + endpoint: TestConfiguration.AzureOpenAI.Endpoint, |
| 60 | + apiKey: TestConfiguration.AzureOpenAI.ApiKey, |
| 61 | + modelId: TestConfiguration.AzureOpenAI.ChatModelId) |
| 62 | + .Build(); |
| 63 | + |
| 64 | + var settings = new OpenAIPromptExecutionSettings |
| 65 | + { |
| 66 | + MaxTokens = 1500, |
| 67 | + Temperature = 0.7, |
| 68 | + TopP = 1.0, |
| 69 | + PresencePenalty = 0.0, |
| 70 | + FrequencyPenalty = 0.0, |
| 71 | + }; |
| 72 | + |
| 73 | + var fitnessTrainer = new ChatCompletionAgent( |
| 74 | + kernel, |
| 75 | + instructions: "As a fitness trainer, suggest workout routines, and exercises for beginners. " + |
| 76 | + "You are not a stress management expert, so refrain from recommending stress management strategies. " + |
| 77 | + "Collaborate with the stress management expert to create a holistic wellness plan." + |
| 78 | + "Always incorporate stress reduction techniques provided by the stress management expert into the fitness plan." + |
| 79 | + "Always include your role at the beginning of each response, such as 'As a fitness trainer.", |
| 80 | + settings |
| 81 | + ); |
| 82 | + |
| 83 | + var stressManagementExpert = new ChatCompletionAgent( |
| 84 | + kernel, |
| 85 | + instructions: "As a stress management expert, provide guidance on stress reduction strategies. " + |
| 86 | + "Collaborate with the fitness trainer to create a simple and holistic wellness plan." + |
| 87 | + "You are not a fitness expert; therefore, avoid recommending fitness exercises." + |
| 88 | + "If the plan is not aligned with recommended stress reduction plan, ask the fitness trainer to rework it to incorporate recommended stress reduction techniques. " + |
| 89 | + "Only you can stop the conversation by saying WELLNESS_PLAN_COMPLETE if suggested fitness plan is good." + |
| 90 | + "Always include your role at the beginning of each response such as 'As a stress management expert.", |
| 91 | + settings |
| 92 | + ); |
| 93 | + |
| 94 | + var chat = new TurnBasedChat(new[] { fitnessTrainer, stressManagementExpert }, (chatHistory, replies, turn) => |
| 95 | + turn >= 10 || // Limit the number of turns to 10 |
| 96 | + replies.Any( |
| 97 | + message => message.Role == AuthorRole.Assistant && |
| 98 | + message.Content!.Contains("WELLNESS_PLAN_COMPLETE", StringComparison.InvariantCulture))); // Exit when the message "WELLNESS_PLAN_COMPLETE" received from agent |
| 99 | + |
| 100 | + var prompt = "I need help creating a simple wellness plan for a beginner. Please guide me."; |
| 101 | + PrintConversation(await chat.SendMessageAsync(prompt)); |
| 102 | + } |
| 103 | + |
| 104 | + private string PrintPrompt(string prompt) |
| 105 | + { |
| 106 | + this.WriteLine($"Prompt: {prompt}"); |
| 107 | + |
| 108 | + return prompt; |
| 109 | + } |
| 110 | + |
| 111 | + private void PrintConversation(IEnumerable<ChatMessageContent> messages) |
| 112 | + { |
| 113 | + foreach (var message in messages) |
| 114 | + { |
| 115 | + this.WriteLine($"------------------------------- {message.Role} ------------------------------"); |
| 116 | + this.WriteLine(message.Content); |
| 117 | + this.WriteLine(); |
| 118 | + } |
| 119 | + |
| 120 | + this.WriteLine(); |
| 121 | + } |
| 122 | + |
| 123 | + private sealed class TurnBasedChat |
| 124 | + { |
| 125 | + public TurnBasedChat(IEnumerable<ChatCompletionAgent> agents, Func<ChatHistory, IEnumerable<ChatMessageContent>, int, bool> exitCondition) |
| 126 | + { |
| 127 | + this._agents = agents.ToArray(); |
| 128 | + this._exitCondition = exitCondition; |
| 129 | + } |
| 130 | + |
| 131 | + public async Task<IReadOnlyList<ChatMessageContent>> SendMessageAsync(string message, CancellationToken cancellationToken = default) |
| 132 | + { |
| 133 | + var chat = new ChatHistory(); |
| 134 | + chat.AddUserMessage(message); |
| 135 | + |
| 136 | + IReadOnlyList<ChatMessageContent> result = new List<ChatMessageContent>(); |
| 137 | + |
| 138 | + var turn = 0; |
| 139 | + |
| 140 | + do |
| 141 | + { |
| 142 | + var agent = this._agents[turn % this._agents.Length]; |
| 143 | + |
| 144 | + result = await agent.InvokeAsync(chat, cancellationToken); |
| 145 | + |
| 146 | + chat.AddRange(result); |
| 147 | + |
| 148 | + turn++; |
| 149 | + } |
| 150 | + while (!this._exitCondition(chat, result, turn)); |
| 151 | + |
| 152 | + return chat; |
| 153 | + } |
| 154 | + |
| 155 | + private readonly ChatCompletionAgent[] _agents; |
| 156 | + private readonly Func<ChatHistory, IEnumerable<ChatMessageContent>, int, bool> _exitCondition; |
| 157 | + } |
| 158 | + |
| 159 | + public Example79_ChatCompletionAgent(ITestOutputHelper output) : base(output) |
| 160 | + { |
| 161 | + } |
| 162 | +} |
0 commit comments