|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +// This sample demonstrates how to maintain conversation state using the OpenAIResponseClientAgent |
| 4 | +// and AgentThread. By passing the same thread to multiple agent invocations, the agent |
| 5 | +// automatically maintains the conversation history, allowing the AI model to understand |
| 6 | +// context from previous exchanges. |
| 7 | + |
| 8 | +using System.ClientModel; |
| 9 | +using System.ClientModel.Primitives; |
| 10 | +using System.Text.Json; |
| 11 | +using Microsoft.Agents.AI; |
| 12 | +using Microsoft.Extensions.AI; |
| 13 | +using OpenAI; |
| 14 | +using OpenAI.Chat; |
| 15 | +using OpenAI.Conversations; |
| 16 | + |
| 17 | +string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("OPENAI_API_KEY is not set."); |
| 18 | +string model = Environment.GetEnvironmentVariable("OPENAI_MODEL") ?? "gpt-4o-mini"; |
| 19 | + |
| 20 | +// Create a ConversationClient directly from OpenAIClient |
| 21 | +OpenAIClient openAIClient = new(apiKey); |
| 22 | +ConversationClient conversationClient = openAIClient.GetConversationClient(); |
| 23 | + |
| 24 | +// Create an agent directly from the OpenAIResponseClient using OpenAIResponseClientAgent |
| 25 | +ChatClientAgent agent = new(openAIClient.GetOpenAIResponseClient(model).AsIChatClient(), instructions: "You are a helpful assistant.", name: "ConversationAgent"); |
| 26 | + |
| 27 | +ClientResult createConversationResult = await conversationClient.CreateConversationAsync(BinaryContent.Create(BinaryData.FromString("{}"))); |
| 28 | + |
| 29 | +using JsonDocument createConversationResultAsJson = JsonDocument.Parse(createConversationResult.GetRawResponse().Content.ToString()); |
| 30 | +string conversationId = createConversationResultAsJson.RootElement.GetProperty("id"u8)!.GetString()!; |
| 31 | + |
| 32 | +// Create a thread for the conversation - this enables conversation state management for subsequent turns |
| 33 | +AgentThread thread = agent.GetNewThread(conversationId); |
| 34 | + |
| 35 | +Console.WriteLine("=== Multi-turn Conversation Demo ===\n"); |
| 36 | + |
| 37 | +// First turn: Ask about a topic |
| 38 | +Console.WriteLine("User: What is the capital of France?"); |
| 39 | +UserChatMessage firstMessage = new("What is the capital of France?"); |
| 40 | + |
| 41 | +// After this call, the conversation state associated in the options is stored in 'thread' and used in subsequent calls |
| 42 | +ChatCompletion firstResponse = await agent.RunAsync([firstMessage], thread); |
| 43 | +Console.WriteLine($"Assistant: {firstResponse.Content.Last().Text}\n"); |
| 44 | + |
| 45 | +// Second turn: Follow-up question that relies on conversation context |
| 46 | +Console.WriteLine("User: What famous landmarks are located there?"); |
| 47 | +UserChatMessage secondMessage = new("What famous landmarks are located there?"); |
| 48 | + |
| 49 | +ChatCompletion secondResponse = await agent.RunAsync([secondMessage], thread); |
| 50 | +Console.WriteLine($"Assistant: {secondResponse.Content.Last().Text}\n"); |
| 51 | + |
| 52 | +// Third turn: Another follow-up that demonstrates context continuity |
| 53 | +Console.WriteLine("User: How tall is the most famous one?"); |
| 54 | +UserChatMessage thirdMessage = new("How tall is the most famous one?"); |
| 55 | + |
| 56 | +ChatCompletion thirdResponse = await agent.RunAsync([thirdMessage], thread); |
| 57 | +Console.WriteLine($"Assistant: {thirdResponse.Content.Last().Text}\n"); |
| 58 | + |
| 59 | +Console.WriteLine("=== End of Conversation ==="); |
| 60 | + |
| 61 | +// Show full conversation history |
| 62 | +Console.WriteLine("Full Conversation History:"); |
| 63 | +ClientResult getConversationResult = await conversationClient.GetConversationAsync(conversationId); |
| 64 | + |
| 65 | +Console.WriteLine("Conversation created."); |
| 66 | +Console.WriteLine($" Conversation ID: {conversationId}"); |
| 67 | +Console.WriteLine(); |
| 68 | + |
| 69 | +CollectionResult getConversationItemsResults = conversationClient.GetConversationItems(conversationId); |
| 70 | +foreach (ClientResult result in getConversationItemsResults.GetRawPages()) |
| 71 | +{ |
| 72 | + Console.WriteLine("Message contents retrieved. Order is most recent first by default."); |
| 73 | + using JsonDocument getConversationItemsResultAsJson = JsonDocument.Parse(result.GetRawResponse().Content.ToString()); |
| 74 | + foreach (JsonElement element in getConversationItemsResultAsJson.RootElement.GetProperty("data").EnumerateArray()) |
| 75 | + { |
| 76 | + string messageId = element.GetProperty("id"u8).ToString(); |
| 77 | + string messageRole = element.GetProperty("role"u8).ToString(); |
| 78 | + Console.WriteLine($" Message ID: {messageId}"); |
| 79 | + Console.WriteLine($" Message Role: {messageRole}"); |
| 80 | + |
| 81 | + foreach (var content in element.GetProperty("content").EnumerateArray()) |
| 82 | + { |
| 83 | + string messageContentText = content.GetProperty("text"u8).ToString(); |
| 84 | + Console.WriteLine($" Message Text: {messageContentText}"); |
| 85 | + } |
| 86 | + Console.WriteLine(); |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +ClientResult deleteConversationResult = conversationClient.DeleteConversation(conversationId); |
| 91 | +using JsonDocument deleteConversationResultAsJson = JsonDocument.Parse(deleteConversationResult.GetRawResponse().Content.ToString()); |
| 92 | +bool deleted = deleteConversationResultAsJson.RootElement |
| 93 | + .GetProperty("deleted"u8) |
| 94 | + .GetBoolean(); |
| 95 | + |
| 96 | +Console.WriteLine("Conversation deleted."); |
| 97 | +Console.WriteLine($" Deleted: {deleted}"); |
| 98 | +Console.WriteLine(); |
0 commit comments