-
Notifications
You must be signed in to change notification settings - Fork 1.5k
.NET: Add Handoff sample #5245
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lokitoth
wants to merge
2
commits into
main
Choose a base branch
from
dev/dotnet_workflow/add_handoff_sample
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
.NET: Add Handoff sample #5245
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
72 changes: 72 additions & 0 deletions
72
dotnet/samples/03-workflows/Orchestration/Handoff/AgentRegistry.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Agents.AI.Workflows; | ||
| using Microsoft.Extensions.AI; | ||
|
|
||
| /// <summary> | ||
| /// The registry of agents used in the workflow. | ||
| /// </summary> | ||
| /// <param name="chatClient">The <see cref="IChatClient"/> to use as the agent backend.</param> | ||
| internal sealed class AgentRegistry(IChatClient chatClient) | ||
| { | ||
| internal const string IntakeAgentName = "Assistant"; | ||
| public AIAgent IntakeAgent { get; } = chatClient.AsAIAgent( | ||
| instructions: | ||
| """ | ||
| You receive a user request and are responsible for routing to the correct initial expert agent. | ||
| """, | ||
| IntakeAgentName | ||
| ); | ||
|
|
||
| internal const string LiquidityAnalysisAgentName = "Liquidity Analysis"; | ||
| public AIAgent LiquidityAnalysisAgent { get; } = chatClient.AsAIAgent( | ||
| instructions: | ||
| """ | ||
| You are responsible for Liquidity Analysis. | ||
| """, | ||
| LiquidityAnalysisAgentName | ||
| ); | ||
|
|
||
| internal const string TaxAnalysisAgentName = "Tax Analysis"; | ||
| public AIAgent TaxAnalysisAgent { get; } = chatClient.AsAIAgent( | ||
| instructions: | ||
| """ | ||
| You are responsible for Tax Analysis. | ||
| """, | ||
| TaxAnalysisAgentName | ||
| ); | ||
|
|
||
| internal const string ForeignExchangeAgentName = "Foreign Exchange Analysis"; | ||
| public AIAgent ForeignExchangeAgent { get; } = chatClient.AsAIAgent( | ||
| instructions: | ||
| """ | ||
| You are responsible for Foreign Exchange Analysis. | ||
| """, | ||
| ForeignExchangeAgentName | ||
| ); | ||
|
|
||
| internal const string EquityAgentName = "Equity Analysis"; | ||
| public AIAgent EquityAgent { get; } = chatClient.AsAIAgent( | ||
| instructions: | ||
| """ | ||
| You are responsible for Equity Analysis. | ||
| """, | ||
| EquityAgentName | ||
| ); | ||
|
|
||
| public IEnumerable<AIAgent> Experts => [this.LiquidityAnalysisAgent, this.TaxAnalysisAgent, this.ForeignExchangeAgent, this.EquityAgent]; | ||
|
|
||
| public HashSet<AIAgent> All | ||
| { | ||
| get | ||
| { | ||
| if (field == null) | ||
| { | ||
| field = [this.IntakeAgent, .. this.Experts]; | ||
| } | ||
|
|
||
| return field; | ||
| } | ||
| } | ||
| } |
29 changes: 29 additions & 0 deletions
29
dotnet/samples/03-workflows/Orchestration/Handoff/Handoff.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFrameworks>net10.0</TargetFrameworks> | ||
|
|
||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
|
|
||
| <NoWarn>MAAIW001</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Azure.AI.Projects" /> | ||
| <PackageReference Include="Azure.Identity" /> | ||
| <PackageReference Include="Microsoft.Extensions.AI.OpenAI" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows\Microsoft.Agents.AI.Workflows.csproj" /> | ||
| <ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI\Microsoft.Agents.AI.csproj" /> | ||
| <!-- Include Workflows source generator when using [MessageHandler] attribute --> | ||
| <ProjectReference Include="$(RepoRoot)/dotnet/src/Microsoft.Agents.AI.Workflows.Generators/Microsoft.Agents.AI.Workflows.Generators.csproj" | ||
| OutputItemType="Analyzer" | ||
| ReferenceOutputAssembly="false" | ||
| GlobalPropertiesToRemove="TargetFramework" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
24 changes: 24 additions & 0 deletions
24
dotnet/samples/03-workflows/Orchestration/Handoff/Handoff.sln
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| Microsoft Visual Studio Solution File, Format Version 12.00 | ||
| # Visual Studio Version 17 | ||
| VisualStudioVersion = 17.5.2.0 | ||
| MinimumVisualStudioVersion = 10.0.40219.1 | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Handoff", "Handoff.csproj", "{2BF9227D-128C-52CD-C43E-E51BD268AB65}" | ||
| EndProject | ||
| Global | ||
| GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
| Debug|Any CPU = Debug|Any CPU | ||
| Release|Any CPU = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
| {2BF9227D-128C-52CD-C43E-E51BD268AB65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {2BF9227D-128C-52CD-C43E-E51BD268AB65}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {2BF9227D-128C-52CD-C43E-E51BD268AB65}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {2BF9227D-128C-52CD-C43E-E51BD268AB65}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(SolutionProperties) = preSolution | ||
| HideSolutionNode = FALSE | ||
| EndGlobalSection | ||
| GlobalSection(ExtensibilityGlobals) = postSolution | ||
| SolutionGuid = {CF541D9A-AD24-4553-A5A6-2F9FFEDD6C56} | ||
| EndGlobalSection | ||
| EndGlobal |
125 changes: 125 additions & 0 deletions
125
dotnet/samples/03-workflows/Orchestration/Handoff/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using Azure.AI.Projects; | ||
| using Azure.Identity; | ||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Agents.AI.Workflows; | ||
| using Microsoft.Extensions.AI; | ||
|
|
||
| string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") | ||
| ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); | ||
| string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5.4-mini"; | ||
|
|
||
| // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. | ||
| // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid | ||
| // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. | ||
| AIProjectClient projectClient = new(new Uri(endpoint), new DefaultAzureCredential()); | ||
|
|
||
| IChatClient chatClient = projectClient.ProjectOpenAIClient | ||
| .GetChatClient(deploymentName) | ||
| .AsIChatClient(); | ||
|
|
||
| Workflow workflow = CreateWorkflow(chatClient); | ||
|
|
||
| await RunWorkflowAsync(workflow).ConfigureAwait(false); | ||
|
|
||
| static Workflow CreateWorkflow(IChatClient chatClient) | ||
| { | ||
| AgentRegistry agents = new(chatClient); | ||
|
|
||
| HandoffWorkflowBuilder handoffBuilder = AgentWorkflowBuilder.CreateHandoffBuilderWith(agents.IntakeAgent); | ||
|
|
||
| // Add a handoff to each of the experts from every agent in the registry (experts + Intake) | ||
| foreach (AIAgent expert in agents.Experts) | ||
| { | ||
| handoffBuilder.WithHandoffs(agents.All.Except([expert]), expert); | ||
| } | ||
|
|
||
| // Let agents request more user information and return to the asking agent (rather than going back to the intake agent) | ||
| handoffBuilder.EnableReturnToPrevious(); | ||
|
|
||
| return handoffBuilder.Build(); | ||
| } | ||
|
|
||
| static async Task RunWorkflowAsync(Workflow workflow) | ||
| { | ||
| using CancellationTokenSource cts = CreateConsoleCancelKeySource(); | ||
| await using StreamingRun run = await InProcessExecution.OpenStreamingAsync(workflow, cancellationToken: cts.Token) | ||
| .ConfigureAwait(false); | ||
|
|
||
| bool hadError = false; | ||
| do | ||
| { | ||
| Console.Write("> "); | ||
| string userInput = Console.ReadLine() ?? string.Empty; | ||
|
|
||
| if (userInput.Equals("exit", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| break; | ||
| } | ||
|
|
||
| await run.TrySendMessageAsync(userInput); | ||
| string? speakingAgent = null; | ||
| await foreach (WorkflowEvent evt in run.WatchStreamAsync(cts.Token).WithCancellation(cts.Token)) | ||
| { | ||
| switch (evt) | ||
| { | ||
| case AgentResponseUpdateEvent update: | ||
| { | ||
| if (speakingAgent == null || speakingAgent != update.Update.AuthorName) | ||
| { | ||
| speakingAgent = update.Update.AuthorName; | ||
| Console.Write($"\n{speakingAgent}: "); | ||
| } | ||
|
|
||
| Console.Write(update.Update.Text); | ||
| break; | ||
| } | ||
|
|
||
| case WorkflowErrorEvent workflowError: | ||
| { | ||
| Console.ForegroundColor = ConsoleColor.Red; | ||
|
|
||
| if (workflowError.Exception != null) | ||
| { | ||
| Console.WriteLine($"\nWorkflow error: {workflowError.Exception}"); | ||
| } | ||
| else | ||
| { | ||
| Console.WriteLine("\nUnknown workflow error occurred."); | ||
| } | ||
|
|
||
| Console.ResetColor(); | ||
|
|
||
| hadError = true; | ||
| break; | ||
| } | ||
|
|
||
| case WorkflowWarningEvent workflowWarning when workflowWarning.Data is string message: | ||
| { | ||
| Console.ForegroundColor = ConsoleColor.Yellow; | ||
| Console.WriteLine(message); | ||
| Console.ResetColor(); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| } while (!hadError); | ||
| } | ||
|
|
||
| static CancellationTokenSource CreateConsoleCancelKeySource() | ||
| { | ||
| CancellationTokenSource cts = new(); | ||
|
|
||
| // Normally, support a way to detach events, but in this case this is a termination signal, so cleanup will happen | ||
| // as part of application shutdown. | ||
| Console.CancelKeyPress += (s, args) => | ||
| { | ||
| cts.Cancel(); | ||
|
|
||
| // We handle cleanup + termination ourselves | ||
| args.Cancel = true; | ||
| }; | ||
|
|
||
| return cts; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.