Skip to main content

How to Pause a Microsoft Agent Framework Workflow Until a Person Answers in C#

· 13 min read
Jagdish Kumawat
Founder @ Dewiride

A Microsoft Agent Framework workflow can stop in the middle and wait for a person to answer. A request port sends the question out of the workflow, the run halts with the status PendingRequests, and the answer goes back in with CreateResponse. This guide builds a days-off approval that asks a manager to approve 3 days off and finishes with their answer.

Syntax​

Syntax
RequestPort <port> = RequestPort.Create<<TRequest>, <TResponse>>("<portId>");

Workflow <workflow> = new WorkflowBuilder(<firstStep>)
.AddEdge(<stepBefore>, <port>)
.AddEdge(<port>, <stepAfter>)
.WithOutputFrom(<stepAfter>)
.Build();

// After the run halts with the status PendingRequests:
RequestInfoEvent <question> = <run>.OutgoingEvents.OfType<RequestInfoEvent>().Single();
await <run>.ResumeAsync([<question>.Request.CreateResponse(<answer>)]);
PartWhat it is
RequestPort.CreateCreates the port. Its documentation: Creates a new RequestPort instance configured for the specified request and response types.
<TRequest>The type of the question: The type of the request messages that the input port will accept.
<TResponse>The type of the answer: The type of the response messages that the input port will produce.
"<portId>"The unique identifier for the input port.
AddEdge(<stepBefore>, <port>)Sends what <stepBefore> returns to the port, where it becomes the question. So <stepBefore> returns a <TRequest>.
AddEdge(<port>, <stepAfter>)Sends the answer on to <stepAfter>, which takes a <TResponse>.
RequestInfoEventThe event that carries the question. Its Request property is The request to be serviced and data payload associated with it.
CreateResponse(<answer>)Wraps <answer> in a response that carries the ID of the request it answers.
<run>.ResumeAsync([...])Resume execution of the workflow with the provided external responses.

Microsoft's guide to human-in-the-loop workflows describes the round trip: When an executor sends a message to a RequestPort, the request port emits a RequestInfoEvent that contains the details of the request. You don't have to tell the answer where to go: The framework automatically routes the responses back to the appropriate executor based on the original request.

Two run statuses appear in this guide:

StatusMeaning, from Agent Framework 1.28's documentation
PendingRequestsThe run has halted, and has at least one outstanding ExternalRequest.
IdleThe run has halted and has no outstanding requests

The Example​

A console app called DaysOffApproval has a workflow with three steps. DescribeRequest turns a number of days into the question Approve 3 days off?, the request port AskManager sends that question out of the workflow and waits for a yes or a no, and RecordAnswer turns the answer into Days off approved. or Days off rejected.. The app shows the question in the terminal, where you answer as the manager. There's no AI model in it, so you don't need an Azure account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0; this guide used 10.0.404.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, create a console app, move into it and add Agent Framework's workflows package:

Terminal
dotnet new console -o DaysOffApproval
cd DaysOffApproval
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
  • dotnet new console -o DaysOffApproval creates a console app in a new DaysOffApproval folder, and cd moves into it.
  • dotnet add package adds Microsoft.Agents.AI.Workflows, Agent Framework's workflows package: executors, edges, request ports and the code that runs a workflow. --version keeps you on the version this guide used.
Output (shortened)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/DaysOffApproval/DaysOffApproval.csproj:
Restore succeeded.
…
info : PackageReference for package 'Microsoft.Agents.AI.Workflows' version '1.28.0' added to file '/Users/you/source/DaysOffApproval/DaysOffApproval.csproj'.
info : Generating MSBuild file /Users/you/source/DaysOffApproval/obj/DaysOffApproval.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/DaysOffApproval/obj/project.assets.json
log : Restored /Users/you/source/DaysOffApproval/DaysOffApproval.csproj (in 1.56 sec).

The project file now has the package:

DaysOffApproval.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.28.0" />
</ItemGroup>

</Project>

The workflow's steps are plain functions, so this one package is all the project needs.

Step 2: Create the Request Port​

Replace everything in Program.cs with:

Program.cs
using Microsoft.Agents.AI.Workflows;

// A request port: the workflow sends it a question (a string) and waits for the answer (a bool).
RequestPort askManager = RequestPort.Create<string, bool>("AskManager");
  • using Microsoft.Agents.AI.Workflows; lets the code use the workflow types without writing their namespace each time.
  • RequestPort.Create<string, bool>("AskManager") creates a port whose questions are strings and whose answers are bools: true for yes and false for no. AskManager is the port's ID.

Step 3: Connect Two Steps Through the Port​

Add this below the port:

Program.cs (below the port)
Func<int, string> describe = days => $"Approve {days} days off?";
Func<bool, string> record = approved => approved ? "Days off approved." : "Days off rejected.";

ExecutorBinding describeRequest = describe.BindAsExecutor("DescribeRequest");
ExecutorBinding recordAnswer = record.BindAsExecutor("RecordAnswer");

Workflow workflow = new WorkflowBuilder(describeRequest)
.AddEdge(describeRequest, askManager)
.AddEdge(askManager, recordAnswer)
.WithOutputFrom(recordAnswer)
.Build();
  • describe takes the number of days and returns the question. It returns a string, the port's question type.
  • record takes the answer, a bool, which is the port's answer type, and returns the result as text.
  • BindAsExecutor("DescribeRequest") turns a function into an executor, a step of the workflow, with the ID in quotes.
  • AddEdge(describeRequest, askManager) sends the question to the port, and AddEdge(askManager, recordAnswer) sends the answer on to RecordAnswer. The port goes into AddEdge just like a step.
  • WithOutputFrom(recordAnswer) makes what RecordAnswer returns the workflow's output.

The types hold it together: the step before the port returns the question type, string, and the step after it takes the answer type, bool.

Step 4: Start the Run and Read the Question​

Add this below the workflow:

Program.cs (below the workflow)
await using Run run = await InProcessExecution.RunAsync(workflow, 3);
Console.WriteLine($"Status: {await run.GetStatusAsync()}");

// The run stopped at the port. Its question waits in a RequestInfoEvent.
RequestInfoEvent question = run.OutgoingEvents.OfType<RequestInfoEvent>().Single();
question.Request.TryGetDataAs(out string? text);
Console.Write($"{text} (y/n) ");
bool approved = Console.ReadLine()?.Trim().ToLowerInvariant() == "y";
  • InProcessExecution.RunAsync(workflow, 3) runs the workflow inside the app, with 3, the number of days, as its input. Its documentation: The workflow will run until its first halt, and the returned Run will capture all outgoing events. Here the first halt is the question: DescribeRequest runs, the port receives the question, and the run stops. await using disposes of the run when the app ends.
  • GetStatusAsync() reads the run's status.
  • OfType<RequestInfoEvent>().Single() finds the one RequestInfoEvent among the run's events.
  • TryGetDataAs(out string? text) takes the question out of the request and puts it in text. Its documentation: Determines whether the underlying data is of the specified type and outputs the value if it is.
  • Console.Write shows the question with (y/n) after it, and Console.ReadLine() reads what you type. ?.Trim().ToLowerInvariant() == "y" makes approved true for y or Y, and false for anything else.

Step 5: Send the Answer Back​

Add this at the end of the file:

Program.cs (at the end)
// The answer goes back to the request it answers, and the run continues.
await run.ResumeAsync([question.Request.CreateResponse(approved)]);

foreach (WorkflowOutputEvent output in run.NewEvents.OfType<WorkflowOutputEvent>())
{
Console.WriteLine($"Output: {output.Data}");
}

Console.WriteLine($"Status: {await run.GetStatusAsync()}");
  • question.Request.CreateResponse(approved) makes the answer: a response that holds approved and the ID of the request it answers. That ID is the response's RequestId, documented as The unique identifier of the corresponding request.
  • run.ResumeAsync([...]) sends the answer into the run and lets the run continue. The square brackets are a C# collection expression, a list with the one response in it, because ResumeAsync accepts any number of responses.
  • run.NewEvents is documented as Gets all events emitted by the workflow since the last access to NewEvents. This is the first time the app reads it, so it holds the events from before the answer too, and OfType<WorkflowOutputEvent>() keeps only the output.
  • The last line reads the status again, after the answer.

Step 6: Run It and Approve​

Terminal
dotnet run

When the question appears, type y and press Enter:

Output
Status: PendingRequests
Approve 3 days off? (y/n) y
Output: Days off approved.
Status: Idle

macOS-style terminal window titled Terminal — DaysOffApproval showing dotnet run printing Status: PendingRequests, then the question Approve 3 days off? (y/n) answered with y, then Output: Days off approved. and Status: Idle

Line by line:

  1. Status: PendingRequests — the run stopped at the port with the question outstanding.
  2. Approve 3 days off? (y/n) y — the question from the RequestInfoEvent, and the y you typed.
  3. Output: Days off approved. — the port passed true to RecordAnswer, and its result became the workflow's output.
  4. Status: Idle — the run halted again, this time with no request outstanding.

Step 7: Run It Again and Reject​

Terminal
dotnet run

This time, type n and press Enter:

Output
Status: PendingRequests
Approve 3 days off? (y/n) n
Output: Days off rejected.
Status: Idle

macOS-style terminal window titled Terminal — DaysOffApproval showing dotnet run printing Status: PendingRequests, then the question Approve 3 days off? (y/n) answered with n, then Output: Days off rejected. and Status: Idle

The same question got a different answer: RecordAnswer received false, and the output is Days off rejected.. Each dotnet run starts a new run, so the workflow asks its question again from the beginning.

The Complete File​

Program.cs
using Microsoft.Agents.AI.Workflows;

// A request port: the workflow sends it a question (a string) and waits for the answer (a bool).
RequestPort askManager = RequestPort.Create<string, bool>("AskManager");

Func<int, string> describe = days => $"Approve {days} days off?";
Func<bool, string> record = approved => approved ? "Days off approved." : "Days off rejected.";

ExecutorBinding describeRequest = describe.BindAsExecutor("DescribeRequest");
ExecutorBinding recordAnswer = record.BindAsExecutor("RecordAnswer");

Workflow workflow = new WorkflowBuilder(describeRequest)
.AddEdge(describeRequest, askManager)
.AddEdge(askManager, recordAnswer)
.WithOutputFrom(recordAnswer)
.Build();

await using Run run = await InProcessExecution.RunAsync(workflow, 3);
Console.WriteLine($"Status: {await run.GetStatusAsync()}");

// The run stopped at the port. Its question waits in a RequestInfoEvent.
RequestInfoEvent question = run.OutgoingEvents.OfType<RequestInfoEvent>().Single();
question.Request.TryGetDataAs(out string? text);
Console.Write($"{text} (y/n) ");
bool approved = Console.ReadLine()?.Trim().ToLowerInvariant() == "y";

// The answer goes back to the request it answers, and the run continues.
await run.ResumeAsync([question.Request.CreateResponse(approved)]);

foreach (WorkflowOutputEvent output in run.NewEvents.OfType<WorkflowOutputEvent>())
{
Console.WriteLine($"Output: {output.Data}");
}

Console.WriteLine($"Status: {await run.GetStatusAsync()}");

macOS-style code window titled Program.cs — DaysOffApproval showing a request port AskManager created with RequestPort.Create of string and bool, two functions bound as the steps DescribeRequest and RecordAnswer with edges through the port, RunAsync with 3 days, the question read from the RequestInfoEvent and answered from the terminal, and run.ResumeAsync with CreateResponse before the output and status are printed

Common Mistakes​

MistakeWhat happensDo this instead
Looking for the output right after RunAsyncThere's none yet: the run halted at the question with the status PendingRequestsAnswer the RequestInfoEvent first, then read the output
Answering with another type than the port's <TResponse>The documentation says the port throws InvalidOperationException when the response data cannot be interpreted as the expected response typeAnswer with the port's answer type, bool in this example
Using Single() in a workflow that asks several questions at onceSingle() throws when there's more than one RequestInfoEventAnswer every RequestInfoEvent; ResumeAsync takes all the responses in one call
Ending the program while the question waitsThe run lives in the program's memory, so the question is goneSave the run in checkpoints and resume it later

FAQ​

How long can the question wait?​

As long as the program runs: InProcessExecution keeps the run in the program's memory. To ask today and answer tomorrow, save the run in checkpoints and resume it on the next start, as the guide to resuming a workflow from a checkpoint after a restart shows. If a step after the answer can fail, resume from the checkpoint where the run waits instead of the latest one.

Can I answer while the events stream?​

Yes. Microsoft's human-in-the-loop guide starts the workflow with InProcessExecution.RunStreamingAsync, watches the events with WatchStreamAsync, and answers a RequestInfoEvent with SendResponseAsync, passing it Request.CreateResponse(...). The port and the response are the same as here; only the way the app runs the workflow changes.

Can a workflow ask more than once?​

Yes. In Microsoft's guide, the step after the port judges a guessed number, and If it is not correct, it will send another request to ask for a new guess through the RequestPort. Every question is a new RequestInfoEvent, answered the same way.

Does the person have to use the terminal?​

No. The workflow only raises the RequestInfoEvent. How the question reaches a person, in a web page or a chat message for example, is up to your app, and the answer goes back through CreateResponse and ResumeAsync in the same way.

Conclusion​

A request port is the place where a workflow waits for a person. Create it with RequestPort.Create<TRequest, TResponse>, put it between two steps with AddEdge, and the run halts with the status PendingRequests and a RequestInfoEvent that holds the question. Answer with CreateResponse and ResumeAsync, and the run carries on: in the example, y gave Days off approved., n gave Days off rejected., and both runs ended Idle.

Additional Resources​