mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Add circular edges sample.
This commit is contained in:
@@ -55,6 +55,7 @@
|
||||
<Project Path="samples/Durable/Workflow/ConsoleApps/05_WorkflowEvents/05_WorkflowEvents.csproj" />
|
||||
<Project Path="samples/Durable/Workflow/ConsoleApps/06_WorkflowSharedState/06_WorkflowSharedState.csproj" />
|
||||
<Project Path="samples/Durable/Workflow/ConsoleApps/07_SubWorkflows/07_SubWorkflows.csproj" />
|
||||
<Project Path="samples/Durable/Workflow/ConsoleApps/08_WorkflowLoop/08_WorkflowLoop.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/Durable/Workflows/AzureFunctions/">
|
||||
<Project Path="samples/Durable/Workflow/AzureFunctions/01_SequentialWorkflow/01_SequentialWorkflow.csproj" />
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<OutputType>Exe</OutputType>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>WorkflowLoop</AssemblyName>
|
||||
<RootNamespace>WorkflowLoop</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="Microsoft.DurableTask.Client.AzureManaged" />
|
||||
<PackageReference Include="Microsoft.DurableTask.Worker.AzureManaged" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" />
|
||||
<PackageReference Include="Azure.AI.OpenAI" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Local projects that should be switched to package references when using the sample outside of this MAF repo -->
|
||||
<!--
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Agents.AI.DurableTask" />
|
||||
<PackageReference Include="Microsoft.Agents.AI.Workflows" />
|
||||
</ItemGroup>
|
||||
-->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.DurableTask\Microsoft.Agents.AI.DurableTask.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,88 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace WorkflowLoop;
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates slogans and either accepts them or sends feedback back for refinement.
|
||||
/// Uses SendMessageAsync to loop back to SloganWriter and YieldOutputAsync to end the workflow.
|
||||
/// </summary>
|
||||
internal sealed class FeedbackExecutor : Executor<SloganResult>
|
||||
{
|
||||
private readonly AIAgent _agent;
|
||||
private AgentSession? _session;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum rating required to accept a slogan.
|
||||
/// </summary>
|
||||
public int MinimumRating { get; init; } = 9;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum number of refinement attempts before accepting the slogan.
|
||||
/// </summary>
|
||||
public int MaxAttempts { get; init; } = 3;
|
||||
|
||||
private int _attempts;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FeedbackExecutor"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">A unique identifier for the executor.</param>
|
||||
/// <param name="chatClient">The chat client to use for the AI agent.</param>
|
||||
public FeedbackExecutor(string id, IChatClient chatClient) : base(id)
|
||||
{
|
||||
ChatClientAgentOptions agentOptions = new()
|
||||
{
|
||||
ChatOptions = new()
|
||||
{
|
||||
Instructions = "You are a professional editor. You will be given a slogan and the task it is meant to accomplish.",
|
||||
ResponseFormat = ChatResponseFormat.ForJsonSchema<FeedbackResult>()
|
||||
}
|
||||
};
|
||||
|
||||
this._agent = new ChatClientAgent(chatClient, agentOptions);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async ValueTask HandleAsync(SloganResult message, IWorkflowContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Console.WriteLine($" [FeedbackProvider] Evaluating slogan: \"{message.Slogan}\"");
|
||||
this._session ??= await this._agent.GetNewSessionAsync(cancellationToken);
|
||||
|
||||
string sloganMessage = $"""
|
||||
Here is a slogan for the task '{message.Task}':
|
||||
Slogan: {message.Slogan}
|
||||
Please provide feedback on this slogan, including comments, a rating from 1 to 10, and suggested actions for improvement.
|
||||
""";
|
||||
|
||||
AgentResponse response = await this._agent.RunAsync(sloganMessage, this._session, cancellationToken: cancellationToken);
|
||||
FeedbackResult feedback = JsonSerializer.Deserialize<FeedbackResult>(response.Text) ?? throw new InvalidOperationException("Failed to deserialize feedback.");
|
||||
|
||||
Console.WriteLine($" [FeedbackProvider] Rating: {feedback.Rating}/{this.MinimumRating} - {feedback.Comments}");
|
||||
|
||||
// If the rating meets the threshold, accept the slogan and end the workflow
|
||||
if (feedback.Rating >= this.MinimumRating)
|
||||
{
|
||||
Console.WriteLine(" [FeedbackProvider] Accepted!");
|
||||
await context.YieldOutputAsync($"The following slogan was accepted:\n\n{message.Slogan}", cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// If we've exceeded max attempts, accept the slogan anyway
|
||||
if (this._attempts >= this.MaxAttempts)
|
||||
{
|
||||
Console.WriteLine(" [FeedbackProvider] Max attempts reached, accepting final slogan.");
|
||||
await context.YieldOutputAsync($"The slogan was accepted after {this.MaxAttempts} attempts. Final slogan:\n\n{message.Slogan}", cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, send feedback back to the slogan writer for refinement (circular edge)
|
||||
Console.WriteLine($" [FeedbackProvider] Sending back for refinement (attempt {this._attempts + 1}/{this.MaxAttempts})...");
|
||||
await context.SendMessageAsync(feedback, cancellationToken: cancellationToken);
|
||||
this._attempts++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample demonstrates a CYCLIC WORKFLOW (back-edges in the graph).
|
||||
// SloganWriter and FeedbackProvider loop until the slogan meets quality criteria.
|
||||
|
||||
using Azure;
|
||||
using Azure.AI.OpenAI;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI.DurableTask;
|
||||
using Microsoft.Agents.AI.DurableTask.Workflows;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.DurableTask.Client.AzureManaged;
|
||||
using Microsoft.DurableTask.Worker.AzureManaged;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using WorkflowLoop;
|
||||
|
||||
// Get DTS connection string from environment variable
|
||||
string dtsConnectionString = Environment.GetEnvironmentVariable("DURABLE_TASK_SCHEDULER_CONNECTION_STRING")
|
||||
?? "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None";
|
||||
|
||||
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
|
||||
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
|
||||
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT")
|
||||
?? throw new InvalidOperationException("AZURE_OPENAI_DEPLOYMENT is not set.");
|
||||
string? azureOpenAiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_KEY");
|
||||
|
||||
// Create the chat client using key-based or Azure CLI credential authentication
|
||||
AzureOpenAIClient openAiClient = !string.IsNullOrEmpty(azureOpenAiKey)
|
||||
? new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(azureOpenAiKey))
|
||||
: new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential());
|
||||
IChatClient chatClient = openAiClient.GetChatClient(deploymentName).AsIChatClient();
|
||||
|
||||
// Define executors for the workflow
|
||||
SloganWriterExecutor sloganWriter = new("SloganWriter", chatClient);
|
||||
FeedbackExecutor feedbackProvider = new("FeedbackProvider", chatClient);
|
||||
|
||||
// Build the workflow with a circular edge: SloganWriter → FeedbackProvider → SloganWriter
|
||||
Workflow workflow = new WorkflowBuilder(sloganWriter)
|
||||
.WithName("SloganCreationWorkflow")
|
||||
.AddEdge(sloganWriter, feedbackProvider)
|
||||
.AddEdge(feedbackProvider, sloganWriter)
|
||||
.WithOutputFrom(feedbackProvider)
|
||||
.Build();
|
||||
|
||||
IHost host = Host.CreateDefaultBuilder(args)
|
||||
.ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning))
|
||||
.ConfigureServices(services =>
|
||||
{
|
||||
services.ConfigureDurableWorkflows(
|
||||
workflowOptions => workflowOptions.AddWorkflow(workflow),
|
||||
workerBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString),
|
||||
clientBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString));
|
||||
})
|
||||
.Build();
|
||||
|
||||
await host.StartAsync();
|
||||
|
||||
IWorkflowClient workflowClient = host.Services.GetRequiredService<IWorkflowClient>();
|
||||
|
||||
Console.WriteLine("Workflow Loop Demo - Enter a topic for slogan generation (or 'exit'):");
|
||||
|
||||
while (true)
|
||||
{
|
||||
Console.Write("> ");
|
||||
string? input = Console.ReadLine();
|
||||
if (string.IsNullOrWhiteSpace(input) || input.Equals("exit", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// RunAsync starts the workflow; cast to IAwaitableWorkflowRun to wait for the result
|
||||
IAwaitableWorkflowRun run = (IAwaitableWorkflowRun)await workflowClient.RunAsync(workflow, input);
|
||||
Console.WriteLine($"Started run: {run.RunId}");
|
||||
|
||||
string? result = await run.WaitForCompletionAsync<string>();
|
||||
Console.WriteLine($"Result: {result}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Error: {ex.Message}");
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
await host.StopAsync();
|
||||
@@ -0,0 +1,69 @@
|
||||
# Workflow Loop Sample
|
||||
|
||||
This sample demonstrates how to run a **cyclic workflow** (containing loops / back-edges) as a durable orchestration. The workflow iteratively improves a slogan based on AI feedback until it meets quality criteria.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- **Cyclic workflow support** — back-edges in the graph (A → B → A)
|
||||
- **Multi-type executor handlers** — SloganWriter handles both `string` and `FeedbackResult` inputs
|
||||
- **Message routing via `SendMessageAsync`** — FeedbackProvider sends messages back to SloganWriter
|
||||
- **Workflow termination via `YieldOutputAsync`** — FeedbackProvider yields output when the slogan is accepted
|
||||
|
||||
## Overview
|
||||
|
||||
```
|
||||
┌──────────────────────┐
|
||||
│ │
|
||||
input ──→ SloganWriter ──→ FeedbackProvider
|
||||
▲ │
|
||||
│ (FeedbackResult) │
|
||||
└──────────────────────┘
|
||||
back-edge
|
||||
```
|
||||
|
||||
| Executor | Description |
|
||||
|----------|-------------|
|
||||
| SloganWriter | Generates slogans from user input; refines them based on feedback |
|
||||
| FeedbackProvider | Evaluates slogans — accepts (YieldOutput) or loops (SendMessage) |
|
||||
|
||||
### Loop Behavior
|
||||
|
||||
1. **SloganWriter** generates a slogan based on user input
|
||||
2. **FeedbackProvider** evaluates the slogan and provides a rating
|
||||
3. If the rating is below the threshold (default: 9), feedback is sent back to SloganWriter
|
||||
4. SloganWriter improves the slogan based on feedback
|
||||
5. The loop continues until the slogan is accepted or max attempts (default: 3) are reached
|
||||
|
||||
## Environment Setup
|
||||
|
||||
See the [README.md](../README.md) file in the parent directory for information on configuring the environment, including how to install and run the Durable Task Scheduler.
|
||||
|
||||
### Required Environment Variables
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `AZURE_OPENAI_ENDPOINT` | Azure OpenAI endpoint URL |
|
||||
| `AZURE_OPENAI_DEPLOYMENT` | Azure OpenAI deployment name |
|
||||
| `AZURE_OPENAI_KEY` | (Optional) Azure OpenAI API key. If not set, uses Azure CLI credential |
|
||||
| `DURABLE_TASK_SCHEDULER_CONNECTION_STRING` | (Optional) DTS connection string. Defaults to local emulator |
|
||||
|
||||
## Running the Sample
|
||||
|
||||
```bash
|
||||
cd dotnet/samples/Durable/Workflow/ConsoleApps/08_WorkflowLoop
|
||||
dotnet run --framework net10.0
|
||||
```
|
||||
|
||||
### Sample Output
|
||||
|
||||
```text
|
||||
Workflow Loop Demo - Enter a topic for slogan generation (or 'exit'):
|
||||
> sustainable energy
|
||||
Started run: abc123...
|
||||
[FeedbackProvider] Rating 6/9 - sending back for refinement (attempt 1/3)
|
||||
[FeedbackProvider] Rating 8/9 - sending back for refinement (attempt 2/3)
|
||||
Event: WorkflowOutputEvent
|
||||
Completed: The following slogan was accepted:
|
||||
|
||||
Power the future, preserve the planet.
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace WorkflowLoop;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the result produced by the slogan writer executor.
|
||||
/// </summary>
|
||||
public sealed class SloganResult
|
||||
{
|
||||
[JsonPropertyName("task")]
|
||||
public required string Task { get; set; }
|
||||
|
||||
[JsonPropertyName("slogan")]
|
||||
public required string Slogan { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents feedback from the feedback executor, including comments, rating, and improvement actions.
|
||||
/// </summary>
|
||||
public sealed class FeedbackResult
|
||||
{
|
||||
[JsonPropertyName("comments")]
|
||||
public string Comments { get; set; } = string.Empty;
|
||||
|
||||
[JsonPropertyName("rating")]
|
||||
public int Rating { get; set; }
|
||||
|
||||
[JsonPropertyName("actions")]
|
||||
public string Actions { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace WorkflowLoop;
|
||||
|
||||
/// <summary>
|
||||
/// Generates slogans based on user input or refines them based on feedback.
|
||||
/// This executor handles two input types: string (initial request) and FeedbackResult (refinement loop).
|
||||
/// </summary>
|
||||
internal sealed class SloganWriterExecutor : Executor
|
||||
{
|
||||
private readonly AIAgent _agent;
|
||||
private AgentSession? _session;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SloganWriterExecutor"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">A unique identifier for the executor.</param>
|
||||
/// <param name="chatClient">The chat client to use for the AI agent.</param>
|
||||
public SloganWriterExecutor(string id, IChatClient chatClient) : base(id)
|
||||
{
|
||||
ChatClientAgentOptions agentOptions = new()
|
||||
{
|
||||
ChatOptions = new()
|
||||
{
|
||||
Instructions = "You are a professional slogan writer. You will be given a task to create a slogan.",
|
||||
ResponseFormat = ChatResponseFormat.ForJsonSchema<SloganResult>()
|
||||
}
|
||||
};
|
||||
|
||||
this._agent = new ChatClientAgent(chatClient, agentOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures two routes: one for initial string input and one for feedback-based refinement.
|
||||
/// </summary>
|
||||
protected override RouteBuilder ConfigureRoutes(RouteBuilder routeBuilder) =>
|
||||
routeBuilder.AddHandler<string, SloganResult>(this.HandleAsync)
|
||||
.AddHandler<FeedbackResult, SloganResult>(this.HandleFeedbackAsync);
|
||||
|
||||
/// <summary>
|
||||
/// Handles the initial slogan generation request.
|
||||
/// </summary>
|
||||
public async ValueTask<SloganResult> HandleAsync(string message, IWorkflowContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Console.WriteLine($" [SloganWriter] Generating slogan for: {message}");
|
||||
this._session ??= await this._agent.GetNewSessionAsync(cancellationToken);
|
||||
|
||||
AgentResponse result = await this._agent.RunAsync(message, this._session, cancellationToken: cancellationToken);
|
||||
SloganResult slogan = JsonSerializer.Deserialize<SloganResult>(result.Text) ?? throw new InvalidOperationException("Failed to deserialize slogan result.");
|
||||
Console.WriteLine($" [SloganWriter] Generated: \"{slogan.Slogan}\"");
|
||||
return slogan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles feedback from the feedback executor to refine the slogan.
|
||||
/// </summary>
|
||||
public async ValueTask<SloganResult> HandleFeedbackAsync(FeedbackResult message, IWorkflowContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Console.WriteLine($" [SloganWriter] Refining slogan based on feedback (rating was {message.Rating})...");
|
||||
|
||||
string feedbackMessage = $"""
|
||||
Here is the feedback on your previous slogan:
|
||||
Comments: {message.Comments}
|
||||
Rating: {message.Rating}
|
||||
Suggested Actions: {message.Actions}
|
||||
|
||||
Please use this feedback to improve your slogan.
|
||||
""";
|
||||
|
||||
AgentResponse result = await this._agent.RunAsync(feedbackMessage, this._session, cancellationToken: cancellationToken);
|
||||
SloganResult slogan = JsonSerializer.Deserialize<SloganResult>(result.Text) ?? throw new InvalidOperationException("Failed to deserialize slogan result.");
|
||||
Console.WriteLine($" [SloganWriter] Refined: \"{slogan.Slogan}\"");
|
||||
return slogan;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user