mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
904a5b843e
* Python: .NET Samples - Restructure and Improve Samples (Feature Branch) (#4091) * Moved by agent (#4094) * Fix readme links * .NET Samples - Create `04-hosting` learning path step (#4098) * Agent move * Agent reorderd * Remove A2A section from README Removed A2A section from the Getting Started README. * Agent fixed links * Fix broken sample links in durable-agents README (#4101) * Initial plan * Fix broken internal links in documentation Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Revert template link changes; keep only durable-agents README fix Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * .NET Samples - Create `03-workflows` learning path step (#4102) * Fix solution project path * Python: Fix broken markdown links to repo resources (outside /docs) (#4105) * Initial plan * Fix broken markdown links to repo resources Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Update README to rename .NET Workflows Samples section --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * .NET Samples - Create `02-agents` learning path step (#4107) * .NET: Fix broken relative link in GroupChatToolApproval README (#4108) * Initial plan * Fix broken link in GroupChatToolApproval README Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Update labeler configuration for workflow samples * .NET - Reorder Agents samples to start from Step01 instead of Step04 (#4110) * Fix solution * Resolve new sample paths * Move new AgentSkills and AgentWithMemory_Step04 samples * Fix link * Fix readme path * fix: update stale dotnet/samples/Durable path reference in AGENTS.md Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Moved new sample * Update solution * Resolve merge (new sample) * Sync to new sample - FoundryAgents_Step21_BingCustomSearch * Updated README * .NET Samples - Configuration Naming Update (#4149) * .NET: Restore AzureFunctions index parity with ConsoleApps under DurableAgents samples (#4221) * Clean-up `05_host_your_agent` * Config setting consistency * Refine samples * AGENTS.md * Move new samples * Re-order samples * Move new project and fixup solution * Fixup model config * Fix up new UT project --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
214 lines
8.6 KiB
C#
214 lines
8.6 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
|
|
// This sample demonstrates how to use the AG-UI client to connect to a remote AG-UI server
|
|
// and display streaming updates including conversation/response metadata, text content, and errors.
|
|
|
|
using System.CommandLine;
|
|
using System.ComponentModel;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using Microsoft.Agents.AI;
|
|
using Microsoft.Agents.AI.AGUI;
|
|
using Microsoft.Extensions.AI;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace AGUIClient;
|
|
|
|
public static class Program
|
|
{
|
|
public static async Task<int> Main(string[] args)
|
|
{
|
|
// Create root command with options
|
|
RootCommand rootCommand = new("AGUIClient");
|
|
rootCommand.SetAction((_, ct) => HandleCommandsAsync(ct));
|
|
|
|
// Run the command
|
|
return await rootCommand.Parse(args).InvokeAsync();
|
|
}
|
|
|
|
private static async Task HandleCommandsAsync(CancellationToken cancellationToken)
|
|
{
|
|
// Set up the logging
|
|
using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
|
|
{
|
|
builder.AddConsole();
|
|
builder.SetMinimumLevel(LogLevel.Information);
|
|
});
|
|
ILogger logger = loggerFactory.CreateLogger("AGUIClient");
|
|
|
|
// Retrieve configuration settings
|
|
IConfigurationRoot configRoot = new ConfigurationBuilder()
|
|
.AddEnvironmentVariables()
|
|
.AddUserSecrets(Assembly.GetExecutingAssembly())
|
|
.Build();
|
|
|
|
string serverUrl = configRoot["AGUI_SERVER_URL"] ?? "http://localhost:5100";
|
|
|
|
logger.LogInformation("Connecting to AG-UI server at: {ServerUrl}", serverUrl);
|
|
|
|
// Create the AG-UI client agent
|
|
using HttpClient httpClient = new()
|
|
{
|
|
Timeout = TimeSpan.FromSeconds(60)
|
|
};
|
|
|
|
var changeBackground = AIFunctionFactory.Create(
|
|
() =>
|
|
{
|
|
Console.ForegroundColor = ConsoleColor.DarkBlue;
|
|
Console.WriteLine("Changing color to blue");
|
|
},
|
|
name: "change_background_color",
|
|
description: "Change the console background color to dark blue."
|
|
);
|
|
|
|
var readClientClimateSensors = AIFunctionFactory.Create(
|
|
([Description("The sensors measurements to include in the response")] SensorRequest request) =>
|
|
{
|
|
return new SensorResponse()
|
|
{
|
|
Temperature = 22.5,
|
|
Humidity = 45.0,
|
|
AirQualityIndex = 75
|
|
};
|
|
},
|
|
name: "read_client_climate_sensors",
|
|
description: "Reads the climate sensor data from the client device.",
|
|
serializerOptions: AGUIClientSerializerContext.Default.Options
|
|
);
|
|
|
|
var chatClient = new AGUIChatClient(
|
|
httpClient,
|
|
serverUrl,
|
|
jsonSerializerOptions: AGUIClientSerializerContext.Default.Options);
|
|
|
|
AIAgent agent = chatClient.AsAIAgent(
|
|
name: "agui-client",
|
|
description: "AG-UI Client Agent",
|
|
tools: [changeBackground, readClientClimateSensors]);
|
|
|
|
AgentSession session = await agent.CreateSessionAsync(cancellationToken);
|
|
List<ChatMessage> messages = [new(ChatRole.System, "You are a helpful assistant.")];
|
|
try
|
|
{
|
|
while (true)
|
|
{
|
|
// Get user message
|
|
Console.Write("\nUser (:q or quit to exit): ");
|
|
string? message = Console.ReadLine();
|
|
if (string.IsNullOrWhiteSpace(message))
|
|
{
|
|
Console.WriteLine("Request cannot be empty.");
|
|
continue;
|
|
}
|
|
|
|
if (message is ":q" or "quit")
|
|
{
|
|
break;
|
|
}
|
|
|
|
messages.Add(new(ChatRole.User, message));
|
|
|
|
// Call RunStreamingAsync to get streaming updates
|
|
bool isFirstUpdate = true;
|
|
string? sessionId = null;
|
|
var updates = new List<ChatResponseUpdate>();
|
|
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, session, cancellationToken: cancellationToken))
|
|
{
|
|
// Use AsChatResponseUpdate to access ChatResponseUpdate properties
|
|
ChatResponseUpdate chatUpdate = update.AsChatResponseUpdate();
|
|
updates.Add(chatUpdate);
|
|
if (chatUpdate.ConversationId != null)
|
|
{
|
|
sessionId = chatUpdate.ConversationId;
|
|
}
|
|
|
|
// Display run started information from the first update
|
|
if (isFirstUpdate && sessionId != null && update.ResponseId != null)
|
|
{
|
|
Console.ForegroundColor = ConsoleColor.Yellow;
|
|
Console.WriteLine($"\n[Run Started - Session: {sessionId}, Run: {update.ResponseId}]");
|
|
Console.ResetColor();
|
|
isFirstUpdate = false;
|
|
}
|
|
|
|
// Display different content types with appropriate formatting
|
|
foreach (AIContent content in update.Contents)
|
|
{
|
|
switch (content)
|
|
{
|
|
case TextContent textContent:
|
|
Console.ForegroundColor = ConsoleColor.Cyan;
|
|
Console.Write(textContent.Text);
|
|
Console.ResetColor();
|
|
break;
|
|
|
|
case FunctionCallContent functionCallContent:
|
|
Console.ForegroundColor = ConsoleColor.Green;
|
|
Console.WriteLine($"\n[Function Call - Name: {functionCallContent.Name}, Arguments: {PrintArguments(functionCallContent.Arguments)}]");
|
|
Console.ResetColor();
|
|
break;
|
|
|
|
case FunctionResultContent functionResultContent:
|
|
Console.ForegroundColor = ConsoleColor.Magenta;
|
|
if (functionResultContent.Exception != null)
|
|
{
|
|
Console.WriteLine($"\n[Function Result - Exception: {functionResultContent.Exception}]");
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine($"\n[Function Result - Result: {functionResultContent.Result}]");
|
|
}
|
|
Console.ResetColor();
|
|
break;
|
|
|
|
case ErrorContent errorContent:
|
|
Console.ForegroundColor = ConsoleColor.Red;
|
|
string code = errorContent.AdditionalProperties?["Code"] as string ?? "Unknown";
|
|
Console.WriteLine($"\n[Error - Code: {code}, Message: {errorContent.Message}]");
|
|
Console.ResetColor();
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (updates.Count > 0 && !updates[^1].Contents.Any(c => c is TextContent))
|
|
{
|
|
var lastUpdate = updates[^1];
|
|
Console.ForegroundColor = ConsoleColor.Yellow;
|
|
Console.WriteLine();
|
|
Console.WriteLine($"[Run Ended - Session: {sessionId}, Run: {lastUpdate.ResponseId}]");
|
|
Console.ResetColor();
|
|
}
|
|
messages.Clear();
|
|
Console.WriteLine();
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
logger.LogInformation("AGUIClient operation was canceled.");
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException and not ThreadAbortException and not AccessViolationException)
|
|
{
|
|
logger.LogError(ex, "An error occurred while running the AGUIClient");
|
|
return;
|
|
}
|
|
}
|
|
|
|
private static string PrintArguments(IDictionary<string, object?>? arguments)
|
|
{
|
|
if (arguments == null)
|
|
{
|
|
return "";
|
|
}
|
|
var builder = new StringBuilder().AppendLine();
|
|
foreach (var kvp in arguments)
|
|
{
|
|
builder
|
|
.AppendLine($" Name: {kvp.Key}")
|
|
.AppendLine($" Value: {kvp.Value}");
|
|
}
|
|
return builder.ToString();
|
|
}
|
|
}
|