.Net: Add ChatClientAgent Samples - OpenAI Model Client (#72)

* Add Streaming API

* Removing InstructionsRole

* Updating thread notification strategy

* Fix net472 failing

* Small fixes

* Adding Samples for OpenAI

* WIP samples

* default runsettings for unit tests

* Adding first samples with OpenAIModelChatClientAgents

* Removing OpenAI dependency on the sample utility

* Release -> Debug update for GettingStarted project

* Fix GettingStarted.csproj failing to build in Release

* Update dotnet/src/Shared/Samples/BaseSample.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Address PR feedback

* Fix Step 1 samples

* Simplify code

* Address PR feedback

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Roger Barreto
2025-06-12 12:22:07 +00:00
committed by GitHub
co-authored by Copilot
parent d761c92a52
commit 2c75f13337
17 changed files with 822 additions and 6 deletions
@@ -0,0 +1,15 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Extensions.AI;
using Microsoft.Shared.Samples;
using OpenAI;
namespace GettingStarted;
public class AgentSample(ITestOutputHelper output) : BaseSample(output)
{
protected IChatClient GetOpenAIChatClient()
=> new OpenAIClient(TestConfiguration.OpenAI.ApiKey)
.GetChatClient(TestConfiguration.OpenAI.ChatModelId)
.AsIChatClient();
}
@@ -0,0 +1,125 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Agents;
namespace ChatCompletionAgent;
/// <summary>
/// Provides test methods to demonstrate the usage of chat agents with different interaction models.
/// </summary>
/// <remarks>This class contains examples of using <see cref="ChatClientAgent"/> to showcase scenarios with and without conversation history.
/// Each test method demonstrates how to configure and interact with the agents, including handling user input and displaying responses.
/// </remarks>
public sealed class Step01_Running(ITestOutputHelper output) : AgentSample(output)
{
private const string ParrotName = "Parrot";
private const string ParrotInstructions = "Repeat the user message in the voice of a pirate and then end with a parrot sound.";
private const string JokerName = "Joker";
private const string JokerInstructions = "You are good at telling jokes.";
/// <summary>
/// Demonstrate the usage of <see cref="ChatClientAgent"/> where each invocation is
/// a unique interaction with no conversation history between them.
/// </summary>
[Fact]
public async Task RunWithoutThread()
{
// Get the chat client to use for the agent.
using var chatClient = base.GetOpenAIChatClient();
// Define the agent
ChatClientAgent agent =
new(chatClient, new()
{
Name = ParrotName,
Instructions = ParrotInstructions,
});
// Respond to user input
await InvokeAgentAsync("Fortune favors the bold.");
await InvokeAgentAsync("I came, I saw, I conquered.");
await InvokeAgentAsync("Practice makes perfect.");
// Local function to invoke agent and display the conversation messages.
async Task InvokeAgentAsync(string input)
{
this.WriteUserMessage(input);
var response = await agent.RunAsync(input);
this.WriteResponseOutput(response);
}
}
/// <summary>
/// Demonstrate the usage of <see cref="ChatClientAgent"/> where a conversation history is maintained.
/// </summary>
[Fact]
public async Task RunWithConversationThread()
{
// Get the chat client to use for the agent.
using var chatClient = base.GetOpenAIChatClient();
// Define the agent
ChatClientAgent agent =
new(chatClient, new()
{
Name = JokerName,
Instructions = JokerInstructions,
});
// Start a new thread for the agent conversation.
AgentThread thread = agent.GetNewThread();
// Respond to user input
await InvokeAgentAsync("Tell me a joke about a pirate.");
await InvokeAgentAsync("Now add some emojis to the joke.");
// Local function to invoke agent and display the conversation messages for the thread.
async Task InvokeAgentAsync(string input)
{
this.WriteUserMessage(input);
var response = await agent.RunAsync(input, thread);
this.WriteResponseOutput(response);
}
}
/// <summary>
/// Demonstrate the usage of <see cref="ChatClientAgent"/> in streaming mode,
/// where a conversation is maintained by the <see cref="AgentThread"/>.
/// </summary>
[Fact]
public async Task StreamingRunWithConversationThread()
{
// Get the chat client to use for the agent.
using var chatClient = base.GetOpenAIChatClient();
// Define the agent
ChatClientAgent agent =
new(chatClient, new()
{
Name = ParrotName,
Instructions = ParrotInstructions,
});
// Start a new thread for the agent conversation.
AgentThread thread = agent.GetNewThread();
// Respond to user input
await InvokeAgentAsync("Tell me a joke about a pirate.");
await InvokeAgentAsync("Now add some emojis to the joke.");
// Local function to invoke agent and display the conversation messages.
async Task InvokeAgentAsync(string input)
{
this.WriteUserMessage(input);
await foreach (var update in agent.RunStreamingAsync(input, thread))
{
this.WriteAgentOutput(update);
}
}
}
}
@@ -0,0 +1,132 @@
// Copyright (c) Microsoft. All rights reserved.
using System.ComponentModel;
using Microsoft.Agents;
using Microsoft.Extensions.AI;
namespace ChatCompletionAgent;
public sealed class Step02_UsingTools(ITestOutputHelper output) : AgentSample(output)
{
[Fact]
public async Task RunningWithTools()
{
// Get the chat client to use for the agent.
using var chatClient = base.GetOpenAIChatClient();
// Define the agent
ChatClientAgent agent =
new(chatClient, new()
{
Name = "Host",
Instructions = "Answer questions about the menu.",
});
var menuTools = new MenuTools();
var chatOptions = new ChatOptions
{
Tools = [
AIFunctionFactory.Create(menuTools.GetMenu),
AIFunctionFactory.Create(menuTools.GetSpecials),
AIFunctionFactory.Create(menuTools.GetItemPrice),
],
};
// Create the chat history thread to capture the agent interaction.
var thread = agent.GetNewThread();
// Respond to user input, invoking functions where appropriate.
await InvokeAgentAsync("Hello");
await InvokeAgentAsync("What is the special soup and its price?");
await InvokeAgentAsync("What is the special drink and its price?");
await InvokeAgentAsync("Thank you");
async Task InvokeAgentAsync(string input)
{
this.WriteUserMessage(input);
var response = await agent.RunAsync(input, thread, chatOptions: chatOptions);
this.WriteResponseOutput(response);
}
}
[Fact]
public async Task StreamingRunWithTools()
{
// Get the chat client to use for the agent.
using var chatClient = base.GetOpenAIChatClient();
// Define the agent
ChatClientAgent agent =
new(chatClient, new()
{
Name = "Host",
Instructions = "Answer questions about the menu.",
});
var menuTools = new MenuTools();
var chatOptions = new ChatOptions
{
Tools = [
AIFunctionFactory.Create(menuTools.GetMenu),
AIFunctionFactory.Create(menuTools.GetSpecials),
AIFunctionFactory.Create(menuTools.GetItemPrice),
],
};
// Create the chat history thread to capture the agent interaction.
var thread = agent.GetNewThread();
// Respond to user input, invoking functions where appropriate.
await InvokeAgentAsync("Hello");
await InvokeAgentAsync("What is the special soup and its price?");
await InvokeAgentAsync("What is the special drink and its price?");
await InvokeAgentAsync("Thank you");
async Task InvokeAgentAsync(string input)
{
this.WriteUserMessage(input);
await foreach (var update in agent.RunStreamingAsync(input, thread, chatOptions: chatOptions))
{
this.WriteAgentOutput(update);
}
}
}
private sealed class MenuTools
{
[Description("Get the full menu items.")]
public MenuItem[] GetMenu()
{
return s_menuItems;
}
[Description("Get the specials from the menu.")]
public IEnumerable<MenuItem> GetSpecials()
{
return s_menuItems.Where(i => i.IsSpecial);
}
[Description("Get the price of a menu item.")]
public float? GetItemPrice([Description("The name of the menu item.")] string menuItem)
{
return s_menuItems.FirstOrDefault(i => i.Name.Equals(menuItem, StringComparison.OrdinalIgnoreCase))?.Price;
}
private static readonly MenuItem[] s_menuItems = [
new() { Category = "Soup", Name = "Clam Chowder", Price = 4.95f, IsSpecial = true },
new() { Category = "Soup", Name = "Tomato Soup", Price = 4.95f, IsSpecial = false },
new() { Category = "Salad", Name = "Cobb Salad", Price = 9.99f },
new() { Category = "Salad", Name = "House Salad", Price = 4.95f },
new() { Category = "Drink", Name = "Chai Tea", Price = 2.95f, IsSpecial = true },
new() { Category = "Drink", Name = "Soda", Price = 1.95f },
];
public sealed class MenuItem
{
public string Category { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public float Price { get; set; }
public bool IsSpecial { get; set; }
}
}
}
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(ProjectsTargetFrameworks)</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<TargetFrameworks>$(ProjectsDebugTargetFrameworks)</TargetFrameworks>
</PropertyGroup>
<PropertyGroup>
<RootNamespace>GettingStarted</RootNamespace>
<OutputType>Library</OutputType>
<UserSecretsId>5ee045b0-aea3-4f08-8d31-32d1a6f8fed0</UserSecretsId>
<NoWarn>$(NoWarn);CA1707;CA1716;IDE0009;IDE1006;</NoWarn>
<ImplicitUsings>enable</ImplicitUsings>
<InjectSharedSamples>true</InjectSharedSamples>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.Agents\Microsoft.Agents.csproj" />
</ItemGroup>
<PropertyGroup>
<InjectSharedThrow>true</InjectSharedThrow>
</PropertyGroup>
<ItemGroup>
<Using Include="GettingStarted" />
<Using Include="Microsoft.Shared.SampleUtilities" />
</ItemGroup>
</Project>