chore: import upstream snapshot with attribution
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<!--
|
||||
Simulate an AOT / trim-aggressive deployment by disabling System.Text.Json's
|
||||
implicit reflection fallback. When this flag is false, any JSON operation in
|
||||
the process must resolve type info via a source-generated JsonSerializerContext
|
||||
or fail at runtime (the checkpoint pipeline surfaces this as
|
||||
InvalidOperationException: "No JSON type info is available for type 'X'").
|
||||
This is the same constraint that 'dotnet publish -p:PublishAot=true' imposes,
|
||||
observed without requiring a full AOT publish.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="AotCheckpointing.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,38 @@
|
||||
#
|
||||
# This workflow has three discrete actions so each runs in a distinct
|
||||
# superstep, making the checkpoint progression easy to follow.
|
||||
#
|
||||
# 1. SetVariable: capture the user input
|
||||
# 2. InvokeAzureAgent: greet the user via an Azure agent (autoSend on)
|
||||
# 3. SendActivity: emit a closing message
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_aot_demo
|
||||
actions:
|
||||
|
||||
# Capture the user's input
|
||||
- kind: SetVariable
|
||||
id: set_input
|
||||
variable: Local.UserInput
|
||||
value: =System.LastMessage.Text
|
||||
|
||||
# Invoke the greeting agent and stream the response to the user
|
||||
- kind: InvokeAzureAgent
|
||||
id: invoke_greeter
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: GreeterAgent
|
||||
input:
|
||||
messages: =Local.UserInput
|
||||
output:
|
||||
messages: Local.GreeterResponse
|
||||
autoSend: true
|
||||
|
||||
# Emit a closing activity so there is a clear final superstep
|
||||
- kind: SendActivity
|
||||
id: send_summary
|
||||
activity: |-
|
||||
[Sample] Workflow completed. Checkpoints persisted to disk.
|
||||
@@ -0,0 +1,174 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.Agents.AI.Workflows.Checkpointing;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.AotCheckpointing;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrates JSON checkpointing of a declarative workflow under reflection-disabled
|
||||
/// <see cref="System.Text.Json.JsonSerializer"/> (the AOT / trim-aggressive constraint set
|
||||
/// via <c>JsonSerializerIsReflectionEnabledByDefault=false</c> in the csproj).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The key call is <see cref="CheckpointManager.CreateJson(ICheckpointStore{System.Text.Json.JsonElement}, System.Text.Json.JsonSerializerOptions?)"/>
|
||||
/// with <see cref="DeclarativeWorkflowJsonOptions.Default"/>. Drop the options argument to observe the AOT failure. See README.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
await CreateGreeterAgentAsync(foundryEndpoint, configuration);
|
||||
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
Workflow CreateWorkflow()
|
||||
{
|
||||
AzureAgentProvider agentProvider = new(foundryEndpoint, new AzureCliCredential());
|
||||
DeclarativeWorkflowOptions options = new(agentProvider) { Configuration = configuration };
|
||||
string workflowPath = Path.Combine(AppContext.BaseDirectory, "AotCheckpointing.yaml");
|
||||
return DeclarativeWorkflowBuilder.Build<string>(workflowPath, options);
|
||||
}
|
||||
|
||||
DirectoryInfo checkpointFolder = Directory.CreateDirectory(Path.Combine(".", $"chk-{DateTime.Now:yyMMdd-HHmmss-ff}"));
|
||||
try
|
||||
{
|
||||
using FileSystemJsonCheckpointStore store = new(checkpointFolder);
|
||||
|
||||
// KEY LINE: AOT-safe checkpoint manager. Drop the options argument to see the failure.
|
||||
CheckpointManager checkpointManager = CheckpointManager.CreateJson(store, DeclarativeWorkflowJsonOptions.Default);
|
||||
|
||||
Console.WriteLine($"\nCheckpoint folder: {checkpointFolder.FullName}");
|
||||
|
||||
// Phase 1: run + drain. Every [checkpoint x<n>] line is a successful JSON WRITE.
|
||||
List<CheckpointInfo> checkpoints = await RunAndStreamAsync(CreateWorkflow(), workflowInput, checkpointManager).ConfigureAwait(false);
|
||||
|
||||
// Phase 2: prove the JSON READ path. ResumeStreamingAsync deserializes the checkpoint
|
||||
// inside the call; a clean return is the proof. We do not drain the resumed run because
|
||||
// it parks in WaitForInputAsync without a pending external request.
|
||||
if (checkpoints.Count > 0)
|
||||
{
|
||||
CheckpointInfo resumeFromCheckpoint = checkpoints[0];
|
||||
Console.WriteLine($"\nWORKFLOW: Verifying read path by resuming from checkpoint {resumeFromCheckpoint.CheckpointId}");
|
||||
StreamingRun resumed = await InProcessExecution.ResumeStreamingAsync(CreateWorkflow(), resumeFromCheckpoint, checkpointManager).ConfigureAwait(false);
|
||||
await resumed.DisposeAsync().ConfigureAwait(false);
|
||||
Console.WriteLine("WORKFLOW: Checkpoint deserialized successfully");
|
||||
}
|
||||
|
||||
Console.WriteLine("\nWORKFLOW: Done!\n");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDelete(checkpointFolder);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<List<CheckpointInfo>> RunAndStreamAsync(Workflow workflow, string input, CheckpointManager checkpointManager)
|
||||
{
|
||||
StreamingRun run = await InProcessExecution.RunStreamingAsync(workflow, input, checkpointManager).ConfigureAwait(false);
|
||||
return await DrainAsync(run).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<List<CheckpointInfo>> DrainAsync(StreamingRun run)
|
||||
{
|
||||
#pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task
|
||||
await using IAsyncDisposable disposeRun = run;
|
||||
#pragma warning restore CA2007
|
||||
|
||||
List<CheckpointInfo> checkpoints = [];
|
||||
string? streamingMessageId = null;
|
||||
|
||||
await foreach (WorkflowEvent workflowEvent in run.WatchStreamAsync().ConfigureAwait(false))
|
||||
{
|
||||
switch (workflowEvent)
|
||||
{
|
||||
case WorkflowErrorEvent workflowError:
|
||||
throw workflowError.Data as Exception ?? new InvalidOperationException("Unexpected workflow failure.");
|
||||
|
||||
case SuperStepCompletedEvent superStepCompleted:
|
||||
CheckpointInfo? checkpoint = superStepCompleted.CompletionInfo?.Checkpoint;
|
||||
if (checkpoint is not null)
|
||||
{
|
||||
checkpoints.Add(checkpoint);
|
||||
}
|
||||
Console.ForegroundColor = ConsoleColor.DarkGray;
|
||||
Console.WriteLine($"\n[checkpoint x{superStepCompleted.StepNumber}: {checkpoint?.CheckpointId ?? "(none)"}]");
|
||||
Console.ResetColor();
|
||||
break;
|
||||
|
||||
case MessageActivityEvent activityEvent:
|
||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
||||
Console.WriteLine($"\nACTIVITY: {activityEvent.Message.Trim()}");
|
||||
Console.ResetColor();
|
||||
break;
|
||||
|
||||
case AgentResponseUpdateEvent streamEvent:
|
||||
if (!string.Equals(streamingMessageId, streamEvent.Update.MessageId, StringComparison.Ordinal))
|
||||
{
|
||||
streamingMessageId = streamEvent.Update.MessageId;
|
||||
string agentName = streamEvent.Update.AuthorName ?? streamEvent.Update.AgentId ?? nameof(ChatRole.Assistant);
|
||||
Console.ForegroundColor = ConsoleColor.Cyan;
|
||||
Console.Write($"\n{agentName.ToUpperInvariant()}: ");
|
||||
Console.ResetColor();
|
||||
}
|
||||
Console.Write(streamEvent.Update.Text);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return checkpoints;
|
||||
}
|
||||
|
||||
private static async Task CreateGreeterAgentAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
DeclarativeAgentDefinition definition =
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You are a warm and concise greeter. Reply to the user's message in
|
||||
one or two short sentences. Always include the user's name if they
|
||||
provided one, and end with a friendly question.
|
||||
"""
|
||||
};
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "GreeterAgent",
|
||||
agentDefinition: definition,
|
||||
agentDescription: "Greeter agent for the AotCheckpointing sample.");
|
||||
}
|
||||
|
||||
private static void TryDelete(DirectoryInfo directory)
|
||||
{
|
||||
try
|
||||
{
|
||||
directory.Refresh();
|
||||
if (directory.Exists)
|
||||
{
|
||||
directory.Delete(recursive: true);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.DarkYellow;
|
||||
Console.WriteLine($"\n(could not clean up '{directory.FullName}': {ex.Message})");
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
# AotCheckpointing sample
|
||||
|
||||
Demonstrates JSON checkpointing of a declarative workflow under
|
||||
reflection-disabled `System.Text.Json` -- the same constraint imposed by
|
||||
**AOT / trim-aggressive deployments**.
|
||||
|
||||
## What it shows
|
||||
|
||||
- A 3-action declarative workflow
|
||||
(`SetVariable` -> `InvokeAzureAgent` -> `SendActivity`) checkpointed
|
||||
after every superstep.
|
||||
- The csproj sets
|
||||
`<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>`.
|
||||
Every JSON operation must resolve type info via a source-gen
|
||||
`JsonSerializerContext` or fail with
|
||||
`InvalidOperationException: No JSON type info is available for type 'X'`.
|
||||
- The experimental
|
||||
[`DeclarativeWorkflowJsonOptions.Default`](../../../../src/Microsoft.Agents.AI.Workflows.Declarative/DeclarativeWorkflowJsonOptions.cs)
|
||||
`JsonSerializerOptions` instance covers every declarative-package
|
||||
type that flows through the checkpoint pipeline. Pass it to
|
||||
`CheckpointManager.CreateJson`.
|
||||
- JSON round-trip is verified in two phases:
|
||||
1. Run + drain -- every `[checkpoint x<n>]` line is a successful JSON **write**.
|
||||
2. `ResumeStreamingAsync` on a fresh workflow instance -- a clean
|
||||
return is the proof JSON **reads** round-trip too. The resumed run
|
||||
is disposed immediately; without a pending external request it
|
||||
would park in `WaitForInputAsync` indefinitely.
|
||||
|
||||
`DeclarativeWorkflowJsonOptions` is marked
|
||||
`[Experimental("MAAI001")]`. Suppress that diagnostic in your csproj to
|
||||
use it.
|
||||
|
||||
### Registering user-defined types
|
||||
|
||||
For workflows whose inputs or custom `ActionExecutorResult.Result`
|
||||
payloads are user-defined, clone `Default` and append your own resolver:
|
||||
|
||||
```csharp
|
||||
JsonSerializerOptions options = new(DeclarativeWorkflowJsonOptions.Default);
|
||||
options.TypeInfoResolverChain.Add(MyAppJsonContext.Default);
|
||||
options.MakeReadOnly();
|
||||
CheckpointManager manager = CheckpointManager.CreateJson(store, options);
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
Prerequisites:
|
||||
|
||||
- Azure Foundry project with a deployed model.
|
||||
- `az login`.
|
||||
- Configuration (user secrets or env):
|
||||
|
||||
| Setting | Description |
|
||||
| --- | --- |
|
||||
| `AZURE_AI_PROJECT_ENDPOINT` | Foundry project endpoint URL. |
|
||||
| `AZURE_AI_MODEL_DEPLOYMENT_NAME` | Model deployment name. |
|
||||
|
||||
See the [parent README](../README.md) for the full walkthrough.
|
||||
|
||||
```sh
|
||||
cd dotnet/samples/03-workflows/Declarative/AotCheckpointing
|
||||
dotnet run "Hello, my name is Ada."
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
1. `[checkpoint x<n>]` lines after each superstep.
|
||||
2. The agent's streamed response.
|
||||
3. `ACTIVITY: [Sample] Workflow completed. ...`
|
||||
4. `WORKFLOW: Verifying read path by resuming from checkpoint <id>`
|
||||
5. `WORKFLOW: Checkpoint deserialized successfully`
|
||||
6. `WORKFLOW: Done!`
|
||||
|
||||
The `chk-*/` checkpoint folder is deleted at the end.
|
||||
|
||||
## Observe the failure mode
|
||||
|
||||
Drop the options argument:
|
||||
|
||||
```csharp
|
||||
CheckpointManager checkpointManager = CheckpointManager.CreateJson(store, DeclarativeWorkflowJsonOptions.Default);
|
||||
```
|
||||
|
||||
becomes
|
||||
|
||||
```csharp
|
||||
CheckpointManager checkpointManager = CheckpointManager.CreateJson(store);
|
||||
```
|
||||
|
||||
Clean rebuild, then re-run. Expected on the first checkpoint commit:
|
||||
|
||||
```
|
||||
System.InvalidOperationException: No JSON type info is available for type
|
||||
'Microsoft.Agents.AI.Workflows.Declarative.Kit.ActionExecutorResult'.
|
||||
```
|
||||
|
||||
This is what `dotnet publish -p:PublishAot=true` would surface at runtime.
|
||||
|
||||
## Notes
|
||||
|
||||
- `PublishAot=true` is **not** set. The
|
||||
`JsonSerializerIsReflectionEnabledByDefault=false` flag is the
|
||||
minimum constraint that reproduces the AOT failure for JSON
|
||||
checkpointing.
|
||||
- JSON code paths inside transitive dependencies (e.g. Foundry SDK)
|
||||
that rely on reflection would also fail under this flag; those are
|
||||
outside the workflow framework's responsibility.
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="ConfirmInput.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,61 @@
|
||||
#
|
||||
# This workflow demonstrates how to use the Question action
|
||||
# to request user input and confirm it matches the original input.
|
||||
#
|
||||
# Note: This workflow doesn't make use of any agents.
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_demo
|
||||
actions:
|
||||
|
||||
# Capture original input
|
||||
- kind: SetVariable
|
||||
id: set_project
|
||||
variable: Local.OriginalInput
|
||||
value: =System.LastMessage.Text
|
||||
|
||||
# Request input from user
|
||||
- kind: Question
|
||||
id: question_confirm
|
||||
alwaysPrompt: false
|
||||
autoSend: false
|
||||
property: Local.ConfirmedInput
|
||||
prompt:
|
||||
kind: Message
|
||||
text:
|
||||
- "CONFIRM:"
|
||||
entity:
|
||||
kind: StringPrebuiltEntity
|
||||
|
||||
# Confirm input
|
||||
- kind: ConditionGroup
|
||||
id: check_completion
|
||||
conditions:
|
||||
|
||||
# Didn't match
|
||||
- condition: =Local.OriginalInput <> Local.ConfirmedInput
|
||||
id: check_confirm
|
||||
actions:
|
||||
|
||||
- kind: SendActivity
|
||||
id: sendActivity_mismatch
|
||||
activity: |-
|
||||
"{Local.ConfirmedInput}" does not match the original input of "{Local.OriginalInput}". Please try again.
|
||||
|
||||
- kind: GotoAction
|
||||
id: goto_again
|
||||
actionId: question_confirm
|
||||
|
||||
# Confirmed
|
||||
elseActions:
|
||||
- kind: SendActivity
|
||||
id: sendActivity_confirmed
|
||||
activity: |-
|
||||
You entered:
|
||||
{Local.OriginalInput}
|
||||
|
||||
Confirmed input:
|
||||
{Local.ConfirmedInput}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.ConfirmInput;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate how to use the question action to request user input
|
||||
/// and confirm it matches the original input.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory = new("ConfirmInput.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new();
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(MSBuildThisFileDirectory)..\..\..\..\..\declarative-agents\workflow-samples\CustomerSupport.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,444 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenAI.Responses;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.CustomerSupport;
|
||||
|
||||
/// <summary>
|
||||
/// This workflow demonstrates using multiple agents to provide automated
|
||||
/// troubleshooting steps to resolve common issues with escalation options.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Create the ticketing plugin (mock functionality)
|
||||
TicketingPlugin plugin = new();
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
await CreateAgentsAsync(foundryEndpoint, configuration, plugin);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory =
|
||||
new("CustomerSupport.yaml", foundryEndpoint)
|
||||
{
|
||||
Functions =
|
||||
[
|
||||
AIFunctionFactory.Create(plugin.CreateTicket),
|
||||
AIFunctionFactory.Create(plugin.GetTicket),
|
||||
AIFunctionFactory.Create(plugin.ResolveTicket),
|
||||
AIFunctionFactory.Create(plugin.SendNotification),
|
||||
]
|
||||
};
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new();
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentsAsync(Uri foundryEndpoint, IConfiguration configuration, TicketingPlugin plugin)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "SelfServiceAgent",
|
||||
agentDefinition: DefineSelfServiceAgent(configuration),
|
||||
agentDescription: "Service agent for CustomerSupport workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "TicketingAgent",
|
||||
agentDefinition: DefineTicketingAgent(configuration, plugin),
|
||||
agentDescription: "Ticketing agent for CustomerSupport workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "TicketRoutingAgent",
|
||||
agentDefinition: DefineTicketRoutingAgent(configuration, plugin),
|
||||
agentDescription: "Routing agent for CustomerSupport workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "WindowsSupportAgent",
|
||||
agentDefinition: DefineWindowsSupportAgent(configuration, plugin),
|
||||
agentDescription: "Windows support agent for CustomerSupport workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "TicketResolutionAgent",
|
||||
agentDefinition: DefineResolutionAgent(configuration, plugin),
|
||||
agentDescription: "Resolution agent for CustomerSupport workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "TicketEscalationAgent",
|
||||
agentDefinition: TicketEscalationAgent(configuration, plugin),
|
||||
agentDescription: "Escalate agent for human support");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineSelfServiceAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Use your knowledge to work with the user to provide the best possible troubleshooting steps.
|
||||
|
||||
- If the user confirms that the issue is resolved, then the issue is resolved.
|
||||
- If the user reports that the issue persists, then escalate.
|
||||
""",
|
||||
TextOptions =
|
||||
new ResponseTextOptions
|
||||
{
|
||||
TextFormat =
|
||||
ResponseTextFormat.CreateJsonSchemaFormat(
|
||||
"TaskEvaluation",
|
||||
BinaryData.FromString(
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"IsResolved": {
|
||||
"type": "boolean",
|
||||
"description": "True if the user issue/ask has been resolved."
|
||||
},
|
||||
"NeedsTicket": {
|
||||
"type": "boolean",
|
||||
"description": "True if the user issue/ask requires that a ticket be filed."
|
||||
},
|
||||
"IssueDescription": {
|
||||
"type": "string",
|
||||
"description": "A concise description of the issue."
|
||||
},
|
||||
"AttemptedResolutionSteps": {
|
||||
"type": "string",
|
||||
"description": "An outline of the steps taken to attempt resolution."
|
||||
}
|
||||
},
|
||||
"required": ["IsResolved", "NeedsTicket", "IssueDescription", "AttemptedResolutionSteps"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
"""),
|
||||
jsonSchemaFormatDescription: null,
|
||||
jsonSchemaIsStrict: true),
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineTicketingAgent(IConfiguration configuration, TicketingPlugin plugin) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Always create a ticket in Azure DevOps using the available tools.
|
||||
|
||||
Include the following information in the TicketSummary.
|
||||
|
||||
- Issue description: {{IssueDescription}}
|
||||
- Attempted resolution steps: {{AttemptedResolutionSteps}}
|
||||
|
||||
After creating the ticket, provide the user with the ticket ID.
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
AIFunctionFactory.Create(plugin.CreateTicket).AsOpenAIResponseTool()
|
||||
},
|
||||
StructuredInputs =
|
||||
{
|
||||
["IssueDescription"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "A concise description of the issue.",
|
||||
},
|
||||
["AttemptedResolutionSteps"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "An outline of the steps taken to attempt resolution.",
|
||||
}
|
||||
},
|
||||
TextOptions =
|
||||
new ResponseTextOptions
|
||||
{
|
||||
TextFormat =
|
||||
ResponseTextFormat.CreateJsonSchemaFormat(
|
||||
"TaskEvaluation",
|
||||
BinaryData.FromString(
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"TicketId": {
|
||||
"type": "string",
|
||||
"description": "The identifier of the ticket created in response to the user issue."
|
||||
},
|
||||
"TicketSummary": {
|
||||
"type": "string",
|
||||
"description": "The summary of the ticket created in response to the user issue."
|
||||
}
|
||||
},
|
||||
"required": ["TicketId", "TicketSummary"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
"""),
|
||||
jsonSchemaFormatDescription: null,
|
||||
jsonSchemaIsStrict: true),
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineTicketRoutingAgent(IConfiguration configuration, TicketingPlugin plugin) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Determine how to route the given issue to the appropriate support team.
|
||||
|
||||
Choose from the available teams and their functions:
|
||||
- Windows Activation Support: Windows license activation issues
|
||||
- Windows Support: Windows related issues
|
||||
- Azure Support: Azure related issues
|
||||
- Network Support: Network related issues
|
||||
- Hardware Support: Hardware related issues
|
||||
- Microsoft Office Support: Microsoft Office related issues
|
||||
- General Support: General issues not related to the above categories
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
AIFunctionFactory.Create(plugin.GetTicket).AsOpenAIResponseTool(),
|
||||
},
|
||||
TextOptions =
|
||||
new ResponseTextOptions
|
||||
{
|
||||
TextFormat =
|
||||
ResponseTextFormat.CreateJsonSchemaFormat(
|
||||
"TaskEvaluation",
|
||||
BinaryData.FromString(
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"TeamName": {
|
||||
"type": "string",
|
||||
"description": "The name of the team to route the issue"
|
||||
}
|
||||
},
|
||||
"required": ["TeamName"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
"""),
|
||||
jsonSchemaFormatDescription: null,
|
||||
jsonSchemaIsStrict: true),
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineWindowsSupportAgent(IConfiguration configuration, TicketingPlugin plugin) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Use your knowledge to work with the user to provide the best possible troubleshooting steps
|
||||
for issues related to Windows operating system.
|
||||
|
||||
- Utilize the "Attempted Resolutions Steps" as a starting point for your troubleshooting.
|
||||
- Never escalate without troubleshooting with the user.
|
||||
- If the user confirms that the issue is resolved, then the issue is resolved.
|
||||
- If the user reports that the issue persists, then escalate.
|
||||
|
||||
Issue: {{IssueDescription}}
|
||||
Attempted Resolution Steps: {{AttemptedResolutionSteps}}
|
||||
""",
|
||||
StructuredInputs =
|
||||
{
|
||||
["IssueDescription"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "A concise description of the issue.",
|
||||
},
|
||||
["AttemptedResolutionSteps"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "An outline of the steps taken to attempt resolution.",
|
||||
}
|
||||
},
|
||||
Tools =
|
||||
{
|
||||
AIFunctionFactory.Create(plugin.GetTicket).AsOpenAIResponseTool(),
|
||||
},
|
||||
TextOptions =
|
||||
new ResponseTextOptions
|
||||
{
|
||||
TextFormat =
|
||||
ResponseTextFormat.CreateJsonSchemaFormat(
|
||||
"TaskEvaluation",
|
||||
BinaryData.FromString(
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"IsResolved": {
|
||||
"type": "boolean",
|
||||
"description": "True if the user issue/ask has been resolved."
|
||||
},
|
||||
"NeedsEscalation": {
|
||||
"type": "boolean",
|
||||
"description": "True resolution could not be achieved and the issue/ask requires escalation."
|
||||
},
|
||||
"ResolutionSummary": {
|
||||
"type": "string",
|
||||
"description": "The summary of the steps that led to resolution."
|
||||
}
|
||||
},
|
||||
"required": ["IsResolved", "NeedsEscalation", "ResolutionSummary"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
"""),
|
||||
jsonSchemaFormatDescription: null,
|
||||
jsonSchemaIsStrict: true),
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineResolutionAgent(IConfiguration configuration, TicketingPlugin plugin) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Resolve the following ticket in Azure DevOps.
|
||||
Always include the resolution details.
|
||||
|
||||
- Ticket ID: #{{TicketId}}
|
||||
- Resolution Summary: {{ResolutionSummary}}
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
AIFunctionFactory.Create(plugin.ResolveTicket).AsOpenAIResponseTool(),
|
||||
},
|
||||
StructuredInputs =
|
||||
{
|
||||
["TicketId"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "The identifier of the ticket being resolved.",
|
||||
},
|
||||
["ResolutionSummary"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "The steps taken to resolve the issue.",
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition TicketEscalationAgent(IConfiguration configuration, TicketingPlugin plugin) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You escalate the provided issue to human support team by sending an email if the issue is not resolved.
|
||||
|
||||
Here are some additional details that might help:
|
||||
- TicketId : {{TicketId}}
|
||||
- IssueDescription : {{IssueDescription}}
|
||||
- AttemptedResolutionSteps : {{AttemptedResolutionSteps}}
|
||||
|
||||
Before escalating, gather the user's email address for follow-up.
|
||||
If not known, ask the user for their email address so that the support team can reach them when needed.
|
||||
|
||||
When sending the email, include the following details:
|
||||
- To: support@contoso.com
|
||||
- Cc: user's email address
|
||||
- Subject of the email: "Support Ticket - {TicketId} - [Compact Issue Description]"
|
||||
- Body:
|
||||
- Issue description
|
||||
- Attempted resolution steps
|
||||
- User's email address
|
||||
- Any other relevant information from the conversation history
|
||||
|
||||
Assure the user that their issue will be resolved and provide them with a ticket ID for reference.
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
AIFunctionFactory.Create(plugin.GetTicket).AsOpenAIResponseTool(),
|
||||
AIFunctionFactory.Create(plugin.SendNotification).AsOpenAIResponseTool(),
|
||||
},
|
||||
StructuredInputs =
|
||||
{
|
||||
["TicketId"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "The identifier of the ticket being escalated.",
|
||||
},
|
||||
["IssueDescription"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "A concise description of the issue.",
|
||||
},
|
||||
["ResolutionSummary"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "An outline of the steps taken to attempt resolution.",
|
||||
}
|
||||
},
|
||||
TextOptions =
|
||||
new ResponseTextOptions
|
||||
{
|
||||
TextFormat =
|
||||
ResponseTextFormat.CreateJsonSchemaFormat(
|
||||
"TaskEvaluation",
|
||||
BinaryData.FromString(
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"IsComplete": {
|
||||
"type": "boolean",
|
||||
"description": "Has the email been sent and no more user input is required."
|
||||
},
|
||||
"UserMessage": {
|
||||
"type": "string",
|
||||
"description": "A natural language message to the user."
|
||||
}
|
||||
},
|
||||
"required": ["IsComplete", "UserMessage"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
"""),
|
||||
jsonSchemaFormatDescription: null,
|
||||
jsonSchemaIsStrict: true),
|
||||
}
|
||||
};
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Default": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Reboot": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"My PC keeps rebooting and I can't use it.\""
|
||||
},
|
||||
"License": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"My M365 Office license key isn't activating.\""
|
||||
},
|
||||
"Windows": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"How do I change my mouse speed settings?\""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Demo.Workflows.Declarative.CustomerSupport;
|
||||
|
||||
internal sealed class TicketingPlugin
|
||||
{
|
||||
private readonly Dictionary<string, TicketItem> _ticketStore = [];
|
||||
|
||||
[Description("Retrieve a ticket by identifier from Azure DevOps.")]
|
||||
public TicketItem? GetTicket(string id)
|
||||
{
|
||||
Trace(nameof(GetTicket));
|
||||
|
||||
this._ticketStore.TryGetValue(id, out TicketItem? ticket);
|
||||
|
||||
return ticket;
|
||||
}
|
||||
|
||||
[Description("Create a ticket in Azure DevOps and return its identifier.")]
|
||||
public string CreateTicket(string subject, string description, string notes)
|
||||
{
|
||||
Trace(nameof(CreateTicket));
|
||||
|
||||
TicketItem ticket = new()
|
||||
{
|
||||
Subject = subject,
|
||||
Description = description,
|
||||
Notes = notes,
|
||||
Id = Guid.NewGuid().ToString("N"),
|
||||
};
|
||||
|
||||
this._ticketStore[ticket.Id] = ticket;
|
||||
|
||||
return ticket.Id;
|
||||
}
|
||||
|
||||
[Description("Resolve an existing ticket in Azure DevOps given its identifier.")]
|
||||
public void ResolveTicket(string id, string resolutionSummary)
|
||||
{
|
||||
Trace(nameof(ResolveTicket));
|
||||
|
||||
if (this._ticketStore.TryGetValue(id, out TicketItem? ticket))
|
||||
{
|
||||
ticket.Status = TicketStatus.Resolved;
|
||||
}
|
||||
}
|
||||
|
||||
[Description("Send an email notification to escalate ticket engagement.")]
|
||||
public void SendNotification(string id, string email, string cc, string body)
|
||||
{
|
||||
Trace(nameof(SendNotification));
|
||||
}
|
||||
|
||||
private static void Trace(string functionName)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.DarkMagenta;
|
||||
try
|
||||
{
|
||||
Console.WriteLine($"\nFUNCTION: {functionName}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
|
||||
public enum TicketStatus
|
||||
{
|
||||
Open,
|
||||
InProgress,
|
||||
Resolved,
|
||||
Closed,
|
||||
}
|
||||
|
||||
public sealed class TicketItem
|
||||
{
|
||||
public TicketStatus Status { get; set; } = TicketStatus.Open;
|
||||
public string Subject { get; init; } = string.Empty;
|
||||
public string Id { get; init; } = string.Empty;
|
||||
public string Description { get; init; } = string.Empty;
|
||||
public string Notes { get; init; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(MSBuildThisFileDirectory)..\..\..\..\..\declarative-agents\workflow-samples\DeepResearch.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="wttr.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,284 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenAI.Responses;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.DeepResearch;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate a declarative workflow that accomplishes a task
|
||||
/// using the Magentic orchestration pattern developed by AutoGen.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
await CreateAgentsAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory = new("DeepResearch.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new();
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentsAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "ResearchAgent",
|
||||
agentDefinition: DefineResearchAgent(configuration),
|
||||
agentDescription: "Planner agent for DeepResearch workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "PlannerAgent",
|
||||
agentDefinition: DefinePlannerAgent(configuration),
|
||||
agentDescription: "Planner agent for DeepResearch workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "ManagerAgent",
|
||||
agentDefinition: DefineManagerAgent(configuration),
|
||||
agentDescription: "Manager agent for DeepResearch workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "SummaryAgent",
|
||||
agentDefinition: DefineSummaryAgent(configuration),
|
||||
agentDescription: "Summary agent for DeepResearch workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "KnowledgeAgent",
|
||||
agentDefinition: DefineKnowledgeAgent(configuration),
|
||||
agentDescription: "Research agent for DeepResearch workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "CoderAgent",
|
||||
agentDefinition: DefineCoderAgent(configuration),
|
||||
agentDescription: "Coder agent for DeepResearch workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "WeatherAgent",
|
||||
agentDefinition: DefineWeatherAgent(configuration),
|
||||
agentDescription: "Weather agent for DeepResearch workflow");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineResearchAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
In order to help begin addressing the user request, please answer the following pre-survey to the best of your ability.
|
||||
Keep in mind that you are Ken Jennings-level with trivia, and Mensa-level with puzzles, so there should be a deep well to draw from.
|
||||
|
||||
Here is the pre-survey:
|
||||
|
||||
1. Please list any specific facts or figures that are GIVEN in the request itself. It is possible that there are none.
|
||||
2. Please list any facts that may need to be looked up, and WHERE SPECIFICALLY they might be found. In some cases, authoritative sources are mentioned in the request itself.
|
||||
3. Please list any facts that may need to be derived (e.g., via logical deduction, simulation, or computation)
|
||||
4. Please list any facts that are recalled from memory, hunches, well-reasoned guesses, etc.
|
||||
|
||||
When answering this survey, keep in mind that 'facts' will typically be specific names, dates, statistics, etc. Your answer must only use the headings:
|
||||
|
||||
1. GIVEN OR VERIFIED FACTS
|
||||
2. FACTS TO LOOK UP
|
||||
3. FACTS TO DERIVE
|
||||
4. EDUCATED GUESSES
|
||||
|
||||
DO NOT include any other headings or sections in your response. DO NOT list next steps or plans until asked to do so.
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
//ProjectsAgentTool.CreateBingGroundingTool( // TODO: Use Bing Grounding when available
|
||||
// new BingGroundingSearchToolParameters(
|
||||
// [new BingGroundingSearchConfiguration(this.GetSetting(Settings.FoundryGroundingTool))]))
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefinePlannerAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions = // TODO: Use Structured Inputs / Prompt Template
|
||||
"""
|
||||
Your only job is to devise an efficient plan that identifies (by name) how a team member may contribute to addressing the user request.
|
||||
|
||||
Only select the following team which is listed as "- [Name]: [Description]"
|
||||
|
||||
- WeatherAgent: Able to retrieve weather information
|
||||
- CoderAgent: Able to write and execute Python code
|
||||
- KnowledgeAgent: Able to perform generic websearches
|
||||
|
||||
The plan must be a bullet point list must be in the form "- [AgentName]: [Specific action or task for that agent to perform]"
|
||||
|
||||
Remember, there is no requirement to involve the entire team -- only select team member's whose particular expertise is required for this task.
|
||||
"""
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineManagerAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions = // TODO: Use Structured Inputs / Prompt Template
|
||||
"""
|
||||
Recall we have assembled the following team:
|
||||
|
||||
- KnowledgeAgent: Able to perform generic websearches
|
||||
- CoderAgent: Able to write and execute Python code
|
||||
- WeatherAgent: Able to retrieve weather information
|
||||
|
||||
To make progress on the request, please answer the following questions, including necessary reasoning:
|
||||
- Is the request fully satisfied? (True if complete, or False if the original request has yet to be SUCCESSFULLY and FULLY addressed)
|
||||
- Are we in a loop where we are repeating the same requests and / or getting the same responses from an agent multiple times? Loops can span multiple turns, and can include repeated actions like scrolling up or down more than a handful of times.
|
||||
- Are we making forward progress? (True if just starting, or recent messages are adding value. False if recent messages show evidence of being stuck in a loop or if there is evidence of significant barriers to success such as the inability to read from a required file)
|
||||
- Who should speak next? (select from: KnowledgeAgent, CoderAgent, WeatherAgent)
|
||||
- What instruction or question would you give this team member? (Phrase as if speaking directly to them, and include any specific information they may need)
|
||||
""",
|
||||
TextOptions =
|
||||
new ResponseTextOptions
|
||||
{
|
||||
TextFormat =
|
||||
ResponseTextFormat.CreateJsonSchemaFormat(
|
||||
"TaskEvaluation",
|
||||
BinaryData.FromString(
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"is_request_satisfied": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reason": { "type": "string" },
|
||||
"answer": { "type": "boolean" }
|
||||
},
|
||||
"required": ["reason", "answer"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"is_in_loop": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reason": { "type": "string" },
|
||||
"answer": { "type": "boolean" }
|
||||
},
|
||||
"required": ["reason", "answer"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"is_progress_being_made": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reason": { "type": "string" },
|
||||
"answer": { "type": "boolean" }
|
||||
},
|
||||
"required": ["reason", "answer"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"next_speaker": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reason": { "type": "string" },
|
||||
"answer": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["reason", "answer"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"instruction_or_question": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reason": { "type": "string" },
|
||||
"answer": { "type": "string" }
|
||||
},
|
||||
"required": ["reason", "answer"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["is_request_satisfied", "is_in_loop", "is_progress_being_made", "next_speaker", "instruction_or_question"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
"""),
|
||||
jsonSchemaFormatDescription: null,
|
||||
jsonSchemaIsStrict: true),
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineSummaryAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
We have completed the task.
|
||||
|
||||
Based only on the conversation and without adding any new information,
|
||||
synthesize the result of the conversation as a complete response to the user task.
|
||||
|
||||
The user will only ever see this last response and not the entire conversation,
|
||||
so please ensure it is complete and self-contained.
|
||||
"""
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineKnowledgeAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Tools =
|
||||
{
|
||||
//ProjectsAgentTool.CreateBingGroundingTool( // TODO: Use Bing Grounding when available
|
||||
// new BingGroundingSearchToolParameters(
|
||||
// [new BingGroundingSearchConfiguration(this.GetSetting(Settings.FoundryGroundingTool))]))
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineCoderAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You solve problem by writing and executing code.
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
ResponseTool.CreateCodeInterpreterTool(
|
||||
new(CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration()))
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineWeatherAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You are a weather expert.
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
ProjectsAgentTool.CreateOpenApiTool(
|
||||
new OpenApiFunctionDefinition(
|
||||
"weather-forecast",
|
||||
BinaryData.FromString(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "wttr.json"))),
|
||||
new OpenAPIAnonymousAuthenticationDetails()))
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Default": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Bus Stop": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"What is the closest bus-stop that is next to ISHONI YAKINIKU in Seattle?\""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "Get weather data",
|
||||
"description": "Retrieves current weather data for a location based on wttr.in.",
|
||||
"version": "v1.0.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "https://wttr.in"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/{location}": {
|
||||
"get": {
|
||||
"description": "Get weather information for a specific location",
|
||||
"operationId": "GetCurrentWeather",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "location",
|
||||
"in": "path",
|
||||
"description": "City or location to retrieve the weather for",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response",
|
||||
"content": {
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Location not found"
|
||||
}
|
||||
},
|
||||
"deprecated": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"schemas": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<NoWarn>$(NoWarn);CA1812</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,237 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// Uncomment this to enable JSON checkpointing to the local file system.
|
||||
//#define CHECKPOINT_JSON
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.DeclarativeWorkflow;
|
||||
|
||||
/// <summary>
|
||||
/// HOW TO: Create a workflow from a declarative (yaml based) definition.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>Configuration</b>
|
||||
/// Define FOUNDRY_PROJECT_ENDPOINT as a user-secret or environment variable that
|
||||
/// points to your Foundry project endpoint.
|
||||
/// <b>Usage</b>
|
||||
/// Provide the path to the workflow definition file as the first argument.
|
||||
/// All other arguments are intepreted as a queue of inputs.
|
||||
/// When no input is queued, interactive input is requested from the console.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
string? workflowFile = ParseWorkflowFile(args);
|
||||
if (workflowFile is null)
|
||||
{
|
||||
Notify("\nUsage: DeclarativeWorkflow <workflow-file> [<input>]\n");
|
||||
return;
|
||||
}
|
||||
|
||||
string? workflowInput = ParseWorkflowInput(args);
|
||||
|
||||
Program program = new(workflowFile, workflowInput);
|
||||
await program.ExecuteAsync();
|
||||
}
|
||||
|
||||
private async Task ExecuteAsync()
|
||||
{
|
||||
// Read and parse the declarative workflow.
|
||||
Notify($"\nWORKFLOW: Parsing {Path.GetFullPath(this.WorkflowFile)}");
|
||||
|
||||
Stopwatch timer = Stopwatch.StartNew();
|
||||
|
||||
Workflow workflow = this.CreateWorkflow();
|
||||
|
||||
Notify($"\nWORKFLOW: Defined {timer.Elapsed}");
|
||||
|
||||
Notify("\nWORKFLOW: Starting...");
|
||||
|
||||
string input = this.GetWorkflowInput();
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
await this.Runner.ExecuteAsync(this.CreateWorkflow, input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create the workflow from the declarative YAML. Includes definition of the
|
||||
/// <see cref="DeclarativeWorkflowOptions" /> and the associated <see cref="ResponseAgentProvider"/>.
|
||||
/// </summary>
|
||||
private Workflow CreateWorkflow()
|
||||
{
|
||||
// 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.
|
||||
// Create the agent provider that will service agent requests within the workflow.
|
||||
AzureAgentProvider agentProvider = new(new Uri(this.FoundryEndpoint), new DefaultAzureCredential())
|
||||
{
|
||||
// Functions included here will be auto-executed by the framework.
|
||||
Functions = this.Functions
|
||||
};
|
||||
|
||||
// Define the workflow options.
|
||||
DeclarativeWorkflowOptions options =
|
||||
new(agentProvider)
|
||||
{
|
||||
Configuration = this.Configuration,
|
||||
//ConversationId = null, // Assign to continue a conversation
|
||||
//LoggerFactory = null, // Assign to enable logging
|
||||
};
|
||||
|
||||
// Use DeclarativeWorkflowBuilder to build a workflow based on a YAML file.
|
||||
return DeclarativeWorkflowBuilder.Build<string>(this.WorkflowFile, options);
|
||||
}
|
||||
|
||||
private string WorkflowFile { get; }
|
||||
private string? WorkflowInput { get; }
|
||||
private string FoundryEndpoint { get; }
|
||||
private IConfiguration Configuration { get; }
|
||||
private WorkflowRunner Runner { get; }
|
||||
private IList<AIFunction> Functions { get; }
|
||||
|
||||
private Program(string workflowFile, string? workflowInput)
|
||||
{
|
||||
this.WorkflowFile = workflowFile;
|
||||
this.WorkflowInput = workflowInput;
|
||||
|
||||
this.Configuration = InitializeConfig();
|
||||
|
||||
this.FoundryEndpoint = this.Configuration[Application.Settings.FoundryEndpoint] ?? throw new InvalidOperationException($"Undefined configuration setting: {Application.Settings.FoundryEndpoint}");
|
||||
|
||||
this.Functions =
|
||||
[
|
||||
// Manually define any custom functions that may be required by agents within the workflow.
|
||||
// By default, this sample does not include any functions.
|
||||
//AIFunctionFactory.Create(),
|
||||
];
|
||||
|
||||
this.Runner =
|
||||
new(this.Functions)
|
||||
{
|
||||
#if CHECKPOINT_JSON
|
||||
// Use an json file checkpoint store that will persist checkpoints to the local file system.
|
||||
UseJsonCheckpoints = true
|
||||
#else
|
||||
// Use an in-memory checkpoint store that will not persist checkpoints beyond the lifetime of the process.
|
||||
UseJsonCheckpoints = false
|
||||
#endif
|
||||
};
|
||||
}
|
||||
|
||||
private static string? ParseWorkflowFile(string[] args)
|
||||
{
|
||||
string? workflowFile = args.FirstOrDefault();
|
||||
if (string.IsNullOrWhiteSpace(workflowFile))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!File.Exists(workflowFile) && !Path.IsPathFullyQualified(workflowFile))
|
||||
{
|
||||
string? repoFolder = GetRepoFolder();
|
||||
if (repoFolder is not null)
|
||||
{
|
||||
workflowFile = Path.Combine(repoFolder, "declarative-agents", "workflow-samples", workflowFile);
|
||||
workflowFile = Path.ChangeExtension(workflowFile, ".yaml");
|
||||
}
|
||||
}
|
||||
|
||||
if (!File.Exists(workflowFile))
|
||||
{
|
||||
throw new InvalidOperationException($"Unable to locate workflow: {Path.GetFullPath(workflowFile)}.");
|
||||
}
|
||||
|
||||
return workflowFile;
|
||||
|
||||
static string? GetRepoFolder()
|
||||
{
|
||||
DirectoryInfo? current = new(Directory.GetCurrentDirectory());
|
||||
|
||||
while (current is not null)
|
||||
{
|
||||
if (Directory.Exists(Path.Combine(current.FullName, ".git")))
|
||||
{
|
||||
return current.FullName;
|
||||
}
|
||||
|
||||
current = current.Parent;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private string GetWorkflowInput()
|
||||
{
|
||||
string? input = this.WorkflowInput;
|
||||
|
||||
try
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.DarkGreen;
|
||||
|
||||
Console.Write("\nINPUT: ");
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
Console.WriteLine(input);
|
||||
return input;
|
||||
}
|
||||
while (string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
input = Console.ReadLine();
|
||||
}
|
||||
|
||||
return input.Trim();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ParseWorkflowInput(string[] args)
|
||||
{
|
||||
if (args.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string[] workflowInput = [.. args.Skip(1)];
|
||||
|
||||
return workflowInput.FirstOrDefault();
|
||||
}
|
||||
|
||||
// Load configuration from user-secrets
|
||||
private static IConfigurationRoot InitializeConfig() =>
|
||||
new ConfigurationBuilder()
|
||||
.AddUserSecrets(Assembly.GetExecutingAssembly())
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
|
||||
private static void Notify(string message)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Cyan;
|
||||
try
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Marketing": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Marketing.yaml\" \"An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours\""
|
||||
},
|
||||
"MathChat": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"MathChat.yaml\" \"How would you compute the value of PI?\""
|
||||
},
|
||||
"Question": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Question.yaml\" \"Iko\""
|
||||
},
|
||||
"Research": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"DeepResearch.yaml\" \"What is the closest bus-stop that is next to ISHONI YAKINIKU in Seattle?\""
|
||||
},
|
||||
"ResponseObject": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"ResponseObject.yaml\" \"Can you help me plan a trip somewhere soon?\""
|
||||
},
|
||||
"UserInput": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"UserInput.yaml\" \"Iko\""
|
||||
},
|
||||
"ParseValue": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Pradeep-ParseValue-Number.yaml\" \"Test this case:\""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="FunctionTools.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
#
|
||||
# This workflow demonstrates an agent that requires tool approval
|
||||
# in a loop responding to user input.
|
||||
#
|
||||
# Example input:
|
||||
# What is the soup of the day?
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_demo
|
||||
actions:
|
||||
|
||||
- kind: InvokeAzureAgent
|
||||
id: invoke_search
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: MenuAgent
|
||||
input:
|
||||
externalLoop:
|
||||
when: =Upper(System.LastMessage.Text) <> "EXIT"
|
||||
@@ -0,0 +1,81 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Demo.Workflows.Declarative.FunctionTools;
|
||||
|
||||
#pragma warning disable CA1822 // Mark members as static
|
||||
|
||||
public sealed class MenuPlugin
|
||||
{
|
||||
[Description("Provides a list items on the menu.")]
|
||||
public MenuItem[] GetMenu()
|
||||
{
|
||||
return s_menuItems;
|
||||
}
|
||||
|
||||
[Description("Provides a list of specials from the menu.")]
|
||||
public MenuItem[] GetSpecials()
|
||||
{
|
||||
return [.. s_menuItems.Where(i => i.IsSpecial)];
|
||||
}
|
||||
|
||||
[Description("Provides the price of the requested menu item.")]
|
||||
public float? GetItemPrice(
|
||||
[Description("The name of the menu item.")]
|
||||
string name)
|
||||
{
|
||||
return s_menuItems.FirstOrDefault(i => i.Name.Equals(name, 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; init; } = string.Empty;
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public float Price { get; init; }
|
||||
public bool IsSpecial { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenAI.Responses;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.FunctionTools;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate a workflow that responds to user input using an agent who
|
||||
/// with function tools assigned. Exits the loop when the user enters "exit".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
MenuPlugin menuPlugin = new();
|
||||
AIFunction[] functions =
|
||||
[
|
||||
AIFunctionFactory.Create(menuPlugin.GetMenu),
|
||||
AIFunctionFactory.Create(menuPlugin.GetSpecials),
|
||||
AIFunctionFactory.Create(menuPlugin.GetItemPrice),
|
||||
];
|
||||
|
||||
await CreateAgentAsync(foundryEndpoint, configuration, functions);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory = new("FunctionTools.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new(functions) { UseJsonCheckpoints = true };
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentAsync(Uri foundryEndpoint, IConfiguration configuration, AIFunction[] functions)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "MenuAgent",
|
||||
agentDefinition: DefineMenuAgent(configuration, functions),
|
||||
agentDescription: "Provides information about the restaurant menu");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineMenuAgent(IConfiguration configuration, AIFunction[] functions)
|
||||
{
|
||||
DeclarativeAgentDefinition agentDefinition =
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Answer the users questions on the menu.
|
||||
For questions or input that do not require searching the documentation, inform the
|
||||
user that you can only answer questions what's on the menu.
|
||||
"""
|
||||
};
|
||||
|
||||
foreach (AIFunction function in functions)
|
||||
{
|
||||
agentDefinition.Tools.Add(function.AsOpenAIResponseTool());
|
||||
}
|
||||
|
||||
return agentDefinition;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Default": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Soup": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"What is the soup of the day?\""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<NoWarn>$(NoWarn);CA1812</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(MSBuildThisFileDirectory)..\..\..\..\..\declarative-agents\workflow-samples\MathChat.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,176 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// Uncomment this to enable JSON checkpointing to the local file system.
|
||||
//#define CHECKPOINT_JSON
|
||||
|
||||
using Azure.AI.Extensions.OpenAI;
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Foundry;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.DeclarativeWorkflow;
|
||||
|
||||
/// <summary>
|
||||
/// %%% COMMENT
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>Configuration</b>
|
||||
/// Define FOUNDRY_PROJECT_ENDPOINT as a user-secret or environment variable that
|
||||
/// points to your Foundry project endpoint.
|
||||
/// <b>Usage</b>
|
||||
/// Provide the path to the workflow definition file as the first argument.
|
||||
/// All other arguments are intepreted as a queue of inputs.
|
||||
/// When no input is queued, interactive input is requested from the console.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// 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.
|
||||
// Create the agent service client
|
||||
AIProjectClient aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
await CreateAgentsAsync(aiProjectClient, configuration);
|
||||
|
||||
// Ensure workflow agent exists in Foundry.
|
||||
ProjectsAgentVersion agentVersion = await CreateWorkflowAsync(aiProjectClient, configuration);
|
||||
|
||||
string workflowInput = GetWorkflowInput(args);
|
||||
|
||||
FoundryAgent agent = aiProjectClient.AsAIAgent(agentVersion);
|
||||
|
||||
AgentSession session = await agent.CreateSessionAsync();
|
||||
|
||||
ProjectConversation conversation =
|
||||
await aiProjectClient
|
||||
.GetProjectOpenAIClient()
|
||||
.GetProjectConversationsClient()
|
||||
.CreateProjectConversationAsync()
|
||||
.ConfigureAwait(false);
|
||||
|
||||
Console.WriteLine($"CONVERSATION: {conversation.Id}");
|
||||
|
||||
ChatOptions chatOptions =
|
||||
new()
|
||||
{
|
||||
ConversationId = conversation.Id
|
||||
};
|
||||
ChatClientAgentRunOptions runOptions = new(chatOptions);
|
||||
|
||||
IAsyncEnumerable<AgentResponseUpdate> agentResponseUpdates = agent.RunStreamingAsync(workflowInput, session, runOptions);
|
||||
|
||||
string? lastMessageId = null;
|
||||
await foreach (AgentResponseUpdate responseUpdate in agentResponseUpdates)
|
||||
{
|
||||
if (responseUpdate.MessageId != lastMessageId)
|
||||
{
|
||||
Console.WriteLine($"\n\n{responseUpdate.AuthorName ?? responseUpdate.AgentId}");
|
||||
}
|
||||
|
||||
lastMessageId = responseUpdate.MessageId;
|
||||
|
||||
Console.Write(responseUpdate.Text);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<ProjectsAgentVersion> CreateWorkflowAsync(AIProjectClient agentClient, IConfiguration configuration)
|
||||
{
|
||||
string workflowYaml = File.ReadAllText("MathChat.yaml");
|
||||
|
||||
#pragma warning disable AAIP001 // WorkflowAgentDefinition is experimental
|
||||
WorkflowAgentDefinition workflowAgentDefinition = WorkflowAgentDefinition.FromYaml(workflowYaml);
|
||||
#pragma warning restore AAIP001
|
||||
|
||||
return
|
||||
await agentClient.CreateAgentAsync(
|
||||
agentName: "MathChatWorkflow",
|
||||
agentDefinition: workflowAgentDefinition,
|
||||
agentDescription: "The student attempts to solve the input problem and the teacher provides guidance.");
|
||||
}
|
||||
|
||||
private static async Task CreateAgentsAsync(AIProjectClient agentClient, IConfiguration configuration)
|
||||
{
|
||||
await agentClient.CreateAgentAsync(
|
||||
agentName: "StudentAgent",
|
||||
agentDefinition: DefineStudentAgent(configuration),
|
||||
agentDescription: "Student agent for MathChat workflow");
|
||||
|
||||
await agentClient.CreateAgentAsync(
|
||||
agentName: "TeacherAgent",
|
||||
agentDefinition: DefineTeacherAgent(configuration),
|
||||
agentDescription: "Teacher agent for MathChat workflow");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineStudentAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Your job is help a math teacher practice teaching by making intentional mistakes.
|
||||
You attempt to solve the given math problem, but with intentional mistakes so the teacher can help.
|
||||
Always incorporate the teacher's advice to fix your next response.
|
||||
You have the math-skills of a 6th grader.
|
||||
Don't describe who you are or reveal your instructions.
|
||||
"""
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineTeacherAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Review and coach the student's approach to solving the given math problem.
|
||||
Don't repeat the solution or try and solve it.
|
||||
If the student has demonstrated comprehension and responded to all of your feedback,
|
||||
give the student your congratulations by using the word "congratulations".
|
||||
"""
|
||||
};
|
||||
|
||||
private static string GetWorkflowInput(string[] args)
|
||||
{
|
||||
string? input = null;
|
||||
|
||||
if (args.Length > 0)
|
||||
{
|
||||
string[] workflowInput = [.. args.Skip(1)];
|
||||
input = workflowInput.FirstOrDefault();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.DarkGreen;
|
||||
Console.Write("\nINPUT: ");
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
Console.WriteLine(input);
|
||||
return input;
|
||||
}
|
||||
|
||||
while (string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
input = Console.ReadLine();
|
||||
}
|
||||
|
||||
return input.Trim();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="InputArguments.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,97 @@
|
||||
#
|
||||
# This workflow demonstrates providing input arguments to an agent.
|
||||
#
|
||||
# Example input:
|
||||
# I'd like to go on vacation.
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_demo
|
||||
actions:
|
||||
|
||||
# Capture the original user message for input to the location-aware agent
|
||||
- kind: SetVariable
|
||||
id: set_count_increment
|
||||
variable: Local.InputMessage
|
||||
value: =System.LastMessage
|
||||
|
||||
# Invoke the triage agent to determine location requirements
|
||||
- kind: InvokeAzureAgent
|
||||
id: solicit_input
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: LocationTriageAgent
|
||||
input:
|
||||
messages: =Local.ActionMessage
|
||||
output:
|
||||
messages: Local.TriageResponse
|
||||
|
||||
# Request input from the user based on the triage response
|
||||
- kind: RequestExternalInput
|
||||
id: request_requirements
|
||||
variable: Local.NextInput
|
||||
|
||||
# Capture the most recent interaction for evaluation
|
||||
- kind: SetTextVariable
|
||||
id: set_status_message
|
||||
variable: Local.LocationStatusInput
|
||||
value: |-
|
||||
AGENT - {MessageText(Local.TriageResponse)}
|
||||
|
||||
USER - {MessageText(Local.NextInput)}
|
||||
|
||||
# Evaluate the status of the location triage
|
||||
- kind: InvokeAzureAgent
|
||||
id: evaluate_location
|
||||
agent:
|
||||
name: LocationCaptureAgent
|
||||
input:
|
||||
messages: =UserMessage(Local.LocationStatusInput)
|
||||
output:
|
||||
responseObject: Local.LocationResponse
|
||||
|
||||
# Determine if the location information is complete
|
||||
- kind: ConditionGroup
|
||||
id: check_completion
|
||||
conditions:
|
||||
|
||||
- condition: |-
|
||||
=Local.LocationResponse.is_location_defined = false Or
|
||||
Local.LocationResponse.is_location_confirmed = false
|
||||
id: check_done
|
||||
actions:
|
||||
|
||||
# Capture the action message for input to the triage agent
|
||||
- kind: SetVariable
|
||||
id: set_next_message
|
||||
variable: Local.ActionMessage
|
||||
value: =AgentMessage(Local.LocationResponse.action)
|
||||
|
||||
- kind: GotoAction
|
||||
id: goto_solicit_input
|
||||
actionId: solicit_input
|
||||
|
||||
elseActions:
|
||||
|
||||
# Create a new conversation so the prior context does not interfere
|
||||
- kind: CreateConversation
|
||||
id: conversation_location
|
||||
conversationId: Local.LocationConversationId
|
||||
|
||||
# Invoke the location-aware agent with the location argument
|
||||
# and loop until the user types "EXIT"
|
||||
- kind: InvokeAzureAgent
|
||||
id: location_response
|
||||
conversationId: =Local.LocationConversationId
|
||||
agent:
|
||||
name: LocationAwareAgent
|
||||
input:
|
||||
messages: =Local.InputMessage
|
||||
arguments:
|
||||
location: =Local.LocationResponse.place
|
||||
externalLoop:
|
||||
when: =Upper(System.LastMessage.Text) <> "EXIT"
|
||||
output:
|
||||
autoSend: true
|
||||
@@ -0,0 +1,151 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenAI.Responses;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.InputArguments;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate a workflow that consumes input arguments to dynamically enhance the agent
|
||||
/// instructions. Exits the loop when the user enters "exit".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
await CreateAgentAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory = new("InputArguments.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new();
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "LocationTriageAgent",
|
||||
agentDefinition: DefineLocationTriageAgent(configuration),
|
||||
agentDescription: "Chats with the user to solicit a location of interest.");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "LocationCaptureAgent",
|
||||
agentDefinition: DefineLocationCaptureAgent(configuration),
|
||||
agentDescription: "Evaluate the status of soliciting the location.");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "LocationAwareAgent",
|
||||
agentDefinition: DefineLocationAwareAgent(configuration),
|
||||
agentDescription: "Chats with the user with location awareness.");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineLocationTriageAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Your only job is to solicit a location from the user.
|
||||
|
||||
Always repeat back the location when addressing the user, except when it is not known.
|
||||
"""
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineLocationCaptureAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Request a location from the user. This location could be their own location
|
||||
or perhaps a location they are interested in.
|
||||
|
||||
City level precision is sufficient.
|
||||
|
||||
If extrapolating region and country, confirm you have it right.
|
||||
""",
|
||||
TextOptions =
|
||||
new ResponseTextOptions
|
||||
{
|
||||
TextFormat =
|
||||
ResponseTextFormat.CreateJsonSchemaFormat(
|
||||
"TaskEvaluation",
|
||||
BinaryData.FromString(
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"place": {
|
||||
"type": "string",
|
||||
"description": "Captures only your understanding of the location specified by the user without explanation, or 'unknown' if not yet defined."
|
||||
},
|
||||
"action": {
|
||||
"type": "string",
|
||||
"description": "The instruction for the next action to take regarding the need for additional detail or confirmation."
|
||||
},
|
||||
"is_location_defined": {
|
||||
"type": "boolean",
|
||||
"description": "True if the user location is understood."
|
||||
},
|
||||
"is_location_confirmed": {
|
||||
"type": "boolean",
|
||||
"description": "True if the user location is confirmed. An unambiguous location may be implicitly confirmed without explicit user confirmation."
|
||||
}
|
||||
},
|
||||
"required": ["place", "action", "is_location_defined", "is_location_confirmed"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
"""),
|
||||
jsonSchemaFormatDescription: null,
|
||||
jsonSchemaIsStrict: true),
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineLocationAwareAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
// Parameterized instructions reference the "location" input argument.
|
||||
Instructions =
|
||||
"""
|
||||
Talk to the user about their request.
|
||||
Their request is related to a specific location: {{location}}.
|
||||
""",
|
||||
StructuredInputs =
|
||||
{
|
||||
["location"] =
|
||||
new StructuredInputDefinition
|
||||
{
|
||||
IsRequired = false,
|
||||
DefaultValue = BinaryData.FromString(@"""unknown"""),
|
||||
Description = "The user's location",
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Default": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Vacation": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"I'd like to go on vacation.\""
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
<PackageReference Include="OpenAI" />
|
||||
<PackageReference Include="System.ClientModel" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Mcp\Microsoft.Agents.AI.Workflows.Declarative.Mcp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="InvokeFoundryToolboxMcp.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
#
|
||||
# This workflow demonstrates invoking MCP tools through a Foundry toolbox MCP proxy.
|
||||
#
|
||||
# The toolbox is provisioned with TWO different tool types:
|
||||
# 1. A Foundry built-in web_search tool
|
||||
# 2. A Microsoft Learn MCP server (microsoft_docs)
|
||||
# Both are surfaced through the same MCP-compatible toolbox endpoint.
|
||||
#
|
||||
# The workflow:
|
||||
# 1. Accepts a documentation/web search query as input
|
||||
# 2. Lists the tools exposed by the Foundry toolbox using reserved toolName: tools/list
|
||||
# 3. Invokes the microsoft_docs_search MCP tool
|
||||
# 4. Invokes the built-in web_search tool against the same toolbox endpoint
|
||||
# 5. Uses an agent to summarize and combine both result sets
|
||||
#
|
||||
# Example input:
|
||||
# How do I use Azure OpenAI with my data?
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_invoke_foundry_toolbox_mcp
|
||||
actions:
|
||||
|
||||
# Set the search query from user input.
|
||||
- kind: SetVariable
|
||||
id: set_search_query
|
||||
variable: Local.SearchQuery
|
||||
value: =System.LastMessage.Text
|
||||
|
||||
# List tools exposed by the Foundry toolbox MCP proxy.
|
||||
- kind: InvokeMcpTool
|
||||
id: list_toolbox_tools
|
||||
serverUrl: =Env.FOUNDRY_TOOLBOX_MCP_SERVER_URL
|
||||
serverLabel: foundry_toolbox
|
||||
toolName: tools/list
|
||||
conversationId: =System.ConversationId
|
||||
headers:
|
||||
Foundry-Features: Toolboxes=V1Preview
|
||||
output:
|
||||
autoSend: true
|
||||
result: Local.ToolboxTools
|
||||
|
||||
# Invoke a specific tool exposed through the toolbox and add the result to the conversation.
|
||||
- kind: InvokeMcpTool
|
||||
id: search_docs_with_toolbox
|
||||
serverUrl: =Env.FOUNDRY_TOOLBOX_MCP_SERVER_URL
|
||||
serverLabel: foundry_toolbox
|
||||
toolName: =Env.FOUNDRY_TOOLBOX_DOCS_SERVER_LABEL & "___microsoft_docs_search"
|
||||
conversationId: =System.ConversationId
|
||||
headers:
|
||||
Foundry-Features: Toolboxes=V1Preview
|
||||
arguments:
|
||||
query: =Local.SearchQuery
|
||||
output:
|
||||
autoSend: true
|
||||
result: Local.SearchResult
|
||||
|
||||
# Invoke the web_search built-in tool through the same toolbox proxy. The toolbox surfaces
|
||||
# built-in Foundry tools (like web_search) alongside MCP tools through one MCP-compatible
|
||||
# endpoint. Note that web_search expects argument 'search_query' (not 'query').
|
||||
- kind: InvokeMcpTool
|
||||
id: search_web_with_toolbox
|
||||
serverUrl: =Env.FOUNDRY_TOOLBOX_MCP_SERVER_URL
|
||||
serverLabel: foundry_toolbox
|
||||
toolName: =Env.FOUNDRY_TOOLBOX_WEB_SEARCH_TOOL_NAME
|
||||
conversationId: =System.ConversationId
|
||||
headers:
|
||||
Foundry-Features: Toolboxes=V1Preview
|
||||
arguments:
|
||||
search_query: =Local.SearchQuery
|
||||
output:
|
||||
autoSend: true
|
||||
result: Local.WebSearchResult
|
||||
|
||||
# Use the agent to summarize what happened and answer from the toolbox result.
|
||||
- kind: InvokeAzureAgent
|
||||
id: summarize_toolbox_result
|
||||
agent:
|
||||
name: FoundryToolboxMcpAgent
|
||||
conversationId: =System.ConversationId
|
||||
input:
|
||||
messages: =UserMessage("Combine the Microsoft Learn docs results and the Foundry web search results in the conversation to answer the query " & Local.SearchQuery)
|
||||
output:
|
||||
autoSend: true
|
||||
messages: Local.Summary
|
||||
@@ -0,0 +1,219 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample demonstrates using InvokeMcpTool to call MCP tools through a Foundry toolbox.
|
||||
// It creates a sample toolbox that exposes Microsoft Learn MCP tools, lists the toolbox tools
|
||||
// through the reserved tools/list operation, then calls microsoft_docs_search from the workflow.
|
||||
|
||||
using System.ClientModel;
|
||||
using System.ClientModel.Primitives;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.Http.Headers;
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative.Mcp;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenAI.Responses;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
#pragma warning disable OPENAI001 // Experimental API
|
||||
#pragma warning disable AAIP001 // AgentToolboxes is experimental
|
||||
|
||||
namespace Demo.Workflows.Declarative.InvokeFoundryToolboxMcp;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrates a workflow that uses InvokeMcpTool to call MCP tools exposed through a Foundry toolbox.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This sample provisions a toolbox with Microsoft Learn MCP tools, uses the reserved
|
||||
/// <c>tools/list</c> tool name to list the toolbox tools, calls one specific toolbox tool,
|
||||
/// and has a Foundry agent summarize the results.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
private const string ToolboxNameSetting = "FOUNDRY_TOOLBOX_NAME";
|
||||
private const string ToolboxApiVersionSetting = "FOUNDRY_AGENT_TOOLSET_API_VERSION";
|
||||
private const string ToolboxMcpServerUrlSetting = "FOUNDRY_TOOLBOX_MCP_SERVER_URL";
|
||||
private const string DocsServerLabelSetting = "FOUNDRY_TOOLBOX_DOCS_SERVER_LABEL";
|
||||
private const string WebSearchToolNameSetting = "FOUNDRY_TOOLBOX_WEB_SEARCH_TOOL_NAME";
|
||||
private const string DefaultToolboxName = "declarative_foundry_toolbox_mcp";
|
||||
private const string DefaultToolboxApiVersion = "v1";
|
||||
private const string DefaultDocsServerLabel = "microsoft_docs";
|
||||
private const string DefaultWebSearchToolName = "web_search";
|
||||
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
string toolboxName = configuration[ToolboxNameSetting] ?? DefaultToolboxName;
|
||||
string toolboxApiVersion = configuration[ToolboxApiVersionSetting] ?? DefaultToolboxApiVersion;
|
||||
string docsServerLabel = configuration[DocsServerLabelSetting] ?? DefaultDocsServerLabel;
|
||||
string webSearchToolName = configuration[WebSearchToolNameSetting] ?? DefaultWebSearchToolName;
|
||||
|
||||
// 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.
|
||||
DefaultAzureCredential credential = new();
|
||||
|
||||
// Ensure sample toolbox and agent exist in Foundry
|
||||
string toolboxEndpoint = await CreateSampleToolboxAsync(toolboxName, docsServerLabel, foundryEndpoint, credential);
|
||||
string toolboxMcpServerUrl = BuildToolboxMcpServerUrl(toolboxEndpoint, toolboxName, toolboxApiVersion);
|
||||
IConfiguration workflowConfiguration = new ConfigurationBuilder()
|
||||
.AddConfiguration(configuration)
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
[ToolboxMcpServerUrlSetting] = toolboxMcpServerUrl,
|
||||
[DocsServerLabelSetting] = docsServerLabel,
|
||||
[WebSearchToolNameSetting] = webSearchToolName,
|
||||
})
|
||||
.Build();
|
||||
|
||||
await CreateAgentAsync(foundryEndpoint, configuration, credential);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the MCP tool handler for invoking the Foundry toolbox MCP proxy.
|
||||
ConcurrentBag<HttpClient> createdHttpClients = [];
|
||||
DefaultMcpToolHandler mcpToolHandler = new(
|
||||
httpClientProvider: async (serverUrl, _) =>
|
||||
{
|
||||
await Task.CompletedTask.ConfigureAwait(false);
|
||||
|
||||
if (!string.Equals(serverUrl, toolboxMcpServerUrl, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
FoundryToolboxBearerTokenHandler handler = new(credential)
|
||||
{
|
||||
InnerHandler = new HttpClientHandler()
|
||||
};
|
||||
HttpClient httpClient = new(handler);
|
||||
createdHttpClients.Add(httpClient);
|
||||
return httpClient;
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
// Create the workflow factory with MCP tool provider
|
||||
WorkflowFactory workflowFactory = new("InvokeFoundryToolboxMcp.yaml", foundryEndpoint)
|
||||
{
|
||||
Configuration = workflowConfiguration,
|
||||
McpToolHandler = mcpToolHandler
|
||||
};
|
||||
|
||||
// Execute the workflow
|
||||
WorkflowRunner runner = new() { UseJsonCheckpoints = true };
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Clean up connections and dispose created HttpClients
|
||||
await mcpToolHandler.DisposeAsync();
|
||||
|
||||
foreach (HttpClient httpClient in createdHttpClients)
|
||||
{
|
||||
httpClient.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CreateAgentAsync(Uri foundryEndpoint, IConfiguration configuration, TokenCredential credential)
|
||||
{
|
||||
AIProjectClient aiProjectClient = new(foundryEndpoint, credential);
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "FoundryToolboxMcpAgent",
|
||||
agentDefinition: DefineToolboxAgent(configuration),
|
||||
agentDescription: "Summarizes Foundry toolbox MCP tool results");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineToolboxAgent(IConfiguration configuration)
|
||||
{
|
||||
return new DeclarativeAgentDefinition(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You are a helpful assistant that explains results produced by tools exposed through a Foundry toolbox.
|
||||
The conversation history contains output from BOTH a Microsoft Learn documentation search (MCP) and a Foundry web search.
|
||||
Synthesize an answer that draws on both sources, calls out where they agree or differ, and notes which toolbox tool produced each fact when it is relevant.
|
||||
Be concise.
|
||||
"""
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<string> CreateSampleToolboxAsync(string name, string serverLabel, Uri foundryEndpoint, TokenCredential credential)
|
||||
{
|
||||
AgentAdministrationClientOptions options = new();
|
||||
options.AddPolicy(new FoundryFeaturesPolicy("Toolboxes=V1Preview"), PipelinePosition.PerCall);
|
||||
AgentAdministrationClient adminClient = new(foundryEndpoint, credential, options);
|
||||
AgentToolboxes toolboxClient = adminClient.GetAgentToolboxes();
|
||||
|
||||
try
|
||||
{
|
||||
await toolboxClient.DeleteAsync(name);
|
||||
Console.WriteLine($"Deleted existing toolbox '{name}'");
|
||||
}
|
||||
catch (ClientResultException ex) when (ex.Status == 404)
|
||||
{
|
||||
// Toolbox does not exist.
|
||||
}
|
||||
|
||||
WebSearchToolboxTool webTool = new();
|
||||
|
||||
MCPToolboxTool mcpTool = new(serverLabel)
|
||||
{
|
||||
ServerUri = new Uri("https://learn.microsoft.com/api/mcp"),
|
||||
ToolCallApprovalPolicy = new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval),
|
||||
};
|
||||
|
||||
ToolboxVersion created = (await toolboxClient.CreateVersionAsync(
|
||||
name: name,
|
||||
tools: [webTool, mcpTool],
|
||||
description: "Sample toolbox combining Foundry web search with the Microsoft Learn MCP tools for the declarative InvokeFoundryToolboxMcp sample.")).Value;
|
||||
|
||||
Console.WriteLine($"Created toolbox '{created.Name}' v{created.Version} ({created.Tools.Count} tool(s))");
|
||||
|
||||
return $"{foundryEndpoint.ToString().TrimEnd('/')}/toolboxes";
|
||||
}
|
||||
|
||||
private static string BuildToolboxMcpServerUrl(string toolboxEndpoint, string toolboxName, string apiVersion) =>
|
||||
$"{toolboxEndpoint.TrimEnd('/')}/{toolboxName}/mcp?api-version={Uri.EscapeDataString(apiVersion)}";
|
||||
|
||||
private sealed class FoundryToolboxBearerTokenHandler(TokenCredential credential) : DelegatingHandler
|
||||
{
|
||||
private static readonly TokenRequestContext s_tokenContext =
|
||||
new(["https://ai.azure.com/.default"]);
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
AccessToken token = await credential.GetTokenAsync(s_tokenContext, cancellationToken);
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
|
||||
|
||||
return await base.SendAsync(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FoundryFeaturesPolicy(string feature) : PipelinePolicy
|
||||
{
|
||||
private const string FeatureHeader = "Foundry-Features";
|
||||
|
||||
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
|
||||
{
|
||||
message.Request.Headers.Add(FeatureHeader, feature);
|
||||
ProcessNext(message, pipeline, currentIndex);
|
||||
}
|
||||
|
||||
public override ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
|
||||
{
|
||||
message.Request.Headers.Add(FeatureHeader, feature);
|
||||
return ProcessNextAsync(message, pipeline, currentIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="InvokeFunctionTool.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,55 @@
|
||||
#
|
||||
# This workflow demonstrates using InvokeFunctionTool to call functions directly
|
||||
# from the workflow without going through an AI agent first.
|
||||
#
|
||||
# InvokeFunctionTool allows workflows to:
|
||||
# - Pre-fetch data before calling an AI agent
|
||||
# - Execute operations directly without AI involvement
|
||||
# - Store function results in workflow variables for later use
|
||||
#
|
||||
# Example input:
|
||||
# What are the specials in the menu?
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_invoke_function_tool_demo
|
||||
actions:
|
||||
|
||||
# Invoke GetSpecials function to get today's specials directly from the workflow
|
||||
- kind: InvokeFunctionTool
|
||||
id: invoke_get_specials
|
||||
conversationId: =System.ConversationId
|
||||
requireApproval: true
|
||||
functionName: GetSpecials
|
||||
output:
|
||||
autoSend: true
|
||||
result: Local.Specials
|
||||
messages: Local.FunctionMessage
|
||||
|
||||
# Display a message showing we retrieved the specials
|
||||
- kind: SendMessage
|
||||
id: show_specials_intro
|
||||
message: "Today's specials have been retrieved. Here they are: {Local.Specials}"
|
||||
|
||||
# Now use an agent to format and present the specials to the user
|
||||
- kind: InvokeAzureAgent
|
||||
id: invoke_menu_agent
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: FunctionMenuAgent
|
||||
input:
|
||||
messages: =UserMessage("Please describe today's specials in an appealing way.")
|
||||
output:
|
||||
messages: Local.AgentResponse
|
||||
|
||||
# Allow the user to ask follow-up questions in a loop
|
||||
- kind: InvokeAzureAgent
|
||||
id: invoke_followup
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: FunctionMenuAgent
|
||||
input:
|
||||
externalLoop:
|
||||
when: =Upper(System.LastMessage.Text) <> "EXIT"
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Demo.Workflows.Declarative.InvokeFunctionTool;
|
||||
|
||||
#pragma warning disable CA1822 // Mark members as static
|
||||
|
||||
/// <summary>
|
||||
/// Plugin providing menu-related functions that can be invoked directly by the workflow
|
||||
/// using the InvokeFunctionTool action.
|
||||
/// </summary>
|
||||
public sealed class MenuPlugin
|
||||
{
|
||||
[Description("Provides a list items on the menu.")]
|
||||
public MenuItem[] GetMenu()
|
||||
{
|
||||
return s_menuItems;
|
||||
}
|
||||
|
||||
[Description("Provides a list of specials from the menu.")]
|
||||
public MenuItem[] GetSpecials()
|
||||
{
|
||||
return [.. s_menuItems.Where(i => i.IsSpecial)];
|
||||
}
|
||||
|
||||
[Description("Provides the price of the requested menu item.")]
|
||||
public float? GetItemPrice(
|
||||
[Description("The name of the menu item.")]
|
||||
string name)
|
||||
{
|
||||
return s_menuItems.FirstOrDefault(i => i.Name.Equals(name, 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; init; } = string.Empty;
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public float Price { get; init; }
|
||||
public bool IsSpecial { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenAI.Responses;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.InvokeFunctionTool;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate a workflow that uses InvokeFunctionTool to call functions directly
|
||||
/// from the workflow without going through an AI agent first.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The InvokeFunctionTool action allows workflows to invoke function tools directly,
|
||||
/// enabling pre-fetching of data or executing operations before calling an AI agent.
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Create the menu plugin with functions that can be invoked directly by the workflow
|
||||
MenuPlugin menuPlugin = new();
|
||||
AIFunction[] functions =
|
||||
[
|
||||
AIFunctionFactory.Create(menuPlugin.GetMenu),
|
||||
AIFunctionFactory.Create(menuPlugin.GetSpecials),
|
||||
AIFunctionFactory.Create(menuPlugin.GetItemPrice),
|
||||
];
|
||||
|
||||
// Ensure sample agent exists in Foundry
|
||||
await CreateAgentAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory.
|
||||
WorkflowFactory workflowFactory = new("InvokeFunctionTool.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow
|
||||
WorkflowRunner runner = new(functions) { UseJsonCheckpoints = true };
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
|
||||
AIProjectClient aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "FunctionMenuAgent",
|
||||
agentDefinition: DefineMenuAgent(configuration, []), // Create Agent with no function tool in the definition.
|
||||
agentDescription: "Provides information about the restaurant menu");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineMenuAgent(IConfiguration configuration, AIFunction[] functions)
|
||||
{
|
||||
DeclarativeAgentDefinition agentDefinition =
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Answer the users questions about the menu.
|
||||
Use the information provided in the conversation history to answer questions.
|
||||
If the information is already available in the conversation, use it directly.
|
||||
For questions or input that do not require searching the documentation, inform the
|
||||
user that you can only answer questions about what's on the menu.
|
||||
"""
|
||||
};
|
||||
|
||||
foreach (AIFunction function in functions)
|
||||
{
|
||||
agentDefinition.Tools.Add(function.AsOpenAIResponseTool());
|
||||
}
|
||||
|
||||
return agentDefinition;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="InvokeHttpRequest.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,76 @@
|
||||
#
|
||||
# This workflow demonstrates using HttpRequestAction to call a REST API directly
|
||||
# from the workflow without going through an AI agent first.
|
||||
#
|
||||
# HttpRequestAction allows workflows to:
|
||||
# - Fetch data from external HTTP endpoints
|
||||
# - Store the parsed response in workflow variables for later use
|
||||
# - Add the response body to the conversation so a downstream agent can
|
||||
# answer questions based on it
|
||||
#
|
||||
# This sample fetches public metadata for the dotnet/runtime repository from
|
||||
# the GitHub REST API (no authentication required) and uses an agent to
|
||||
# answer follow-up questions about it.
|
||||
#
|
||||
# Example input:
|
||||
# How many subscribers does the repository have?
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_invoke_http_request_demo
|
||||
actions:
|
||||
|
||||
# Capture the original user message for input to the follow-up agent.
|
||||
- kind: SetVariable
|
||||
id: set_user_message
|
||||
variable: Local.InputMessage
|
||||
value: =System.LastMessage
|
||||
|
||||
# Set the repository org/name used to form the request URL.
|
||||
- kind: SetVariable
|
||||
id: set_repo_name
|
||||
variable: Local.RepoName
|
||||
value: microsoft/agent-framework
|
||||
|
||||
# Invoke the GitHub repo API. The response body is parsed into Local.RepoInfo
|
||||
# and also added to the conversation (via conversationId) so the agent below
|
||||
# can answer questions based on it.
|
||||
- kind: HttpRequestAction
|
||||
id: fetch_repo_info
|
||||
conversationId: =System.ConversationId
|
||||
method: GET
|
||||
url: =Concatenate("https://api.github.com/repos/", Local.RepoName)
|
||||
headers:
|
||||
Accept: application/vnd.github+json
|
||||
User-Agent: agent-framework-sample
|
||||
response: Local.RepoInfo
|
||||
|
||||
# Display a confirmation message showing key fields from the parsed response.
|
||||
- kind: SendMessage
|
||||
id: show_repo_summary
|
||||
message: "Fetched repo: visibility={Local.RepoInfo.visibility}, description={Local.RepoInfo.description}"
|
||||
|
||||
# Use the agent to summarize the repo using the conversation context.
|
||||
- kind: InvokeAzureAgent
|
||||
id: summarize_repo
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: GitHubRepoInfoAgent
|
||||
input:
|
||||
messages: =UserMessage("Please provide a brief summary of this GitHub repository based on the data already in the conversation.")
|
||||
output:
|
||||
autoSend: true
|
||||
messages: Local.AgentResponse
|
||||
|
||||
# Allow the user to ask follow-up questions about the repo in a loop.
|
||||
- kind: InvokeAzureAgent
|
||||
id: invoke_followup
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: GitHubRepoInfoAgent
|
||||
input:
|
||||
messages: =Local.InputMessage
|
||||
externalLoop:
|
||||
when: =Upper(System.LastMessage.Text) <> "EXIT"
|
||||
@@ -0,0 +1,95 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.InvokeHttpRequest;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrates a workflow that uses HttpRequestAction to call a REST API
|
||||
/// directly from the workflow.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The HttpRequestAction allows workflows to issue HTTP requests and:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item>Fetch data from external REST endpoints</item>
|
||||
/// <item>Store the parsed response in workflow variables</item>
|
||||
/// <item>Add the response body to the conversation so an agent can answer
|
||||
/// questions based on it</item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// This sample fetches public metadata for the dotnet/runtime repository from
|
||||
/// the GitHub REST API (no authentication required) and uses a Foundry agent
|
||||
/// to answer follow-up questions about it. Type "EXIT" to end the conversation.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agent exists in Foundry. The agent has no tools - it answers
|
||||
// questions about the GitHub repository using only the JSON data that the
|
||||
// HttpRequestAction adds to the conversation.
|
||||
await CreateAgentAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// The default HttpRequestHandler is sufficient for this sample because the
|
||||
// GitHub REST endpoint used here does not require authentication. For
|
||||
// authenticated endpoints, supply a custom Func<HttpRequestInfo, ..., HttpClient?>
|
||||
// to DefaultHttpRequestHandler so each request can be routed through a
|
||||
// pre-configured (cached) HttpClient with the appropriate credentials.
|
||||
await using DefaultHttpRequestHandler httpRequestHandler = new();
|
||||
|
||||
// Create the workflow factory with the HTTP request handler
|
||||
WorkflowFactory workflowFactory = new("InvokeHttpRequest.yaml", foundryEndpoint)
|
||||
{
|
||||
HttpRequestHandler = httpRequestHandler
|
||||
};
|
||||
|
||||
// Execute the workflow
|
||||
WorkflowRunner runner = new() { UseJsonCheckpoints = true };
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
|
||||
AIProjectClient aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "GitHubRepoInfoAgent",
|
||||
agentDefinition: DefineAgent(configuration),
|
||||
agentDescription: "Answers questions about a GitHub repository using HTTP response data in the conversation");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineAgent(IConfiguration configuration)
|
||||
{
|
||||
return new DeclarativeAgentDefinition(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Answer the user's questions about the GitHub repository using only the
|
||||
JSON data already present in the conversation history.
|
||||
If the answer is not contained in the conversation, say so plainly
|
||||
rather than guessing. Be concise and helpful.
|
||||
"""
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Mcp\Microsoft.Agents.AI.Workflows.Declarative.Mcp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="InvokeMcpTool.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,63 @@
|
||||
#
|
||||
# This workflow demonstrates invoking MCP tools directly from a declarative workflow.
|
||||
# Uses the Foundry MCP server to search AI model details.
|
||||
#
|
||||
# The workflow:
|
||||
# 1. Accepts a model search term as input
|
||||
# 2. Invokes the Foundry MCP tool
|
||||
# 3. Invokes the Microsoft Learn MCP tool
|
||||
# 4. Uses an agent to summarize the results
|
||||
#
|
||||
# Example input:
|
||||
# gpt-5.4-mini
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_invoke_mcp_tool
|
||||
actions:
|
||||
|
||||
# Set the search query from user input or use default
|
||||
- kind: SetVariable
|
||||
id: set_search_query
|
||||
variable: Local.SearchQuery
|
||||
value: =System.LastMessage.Text
|
||||
|
||||
# Invoke MCP search tool on Foundry MCP server
|
||||
- kind: InvokeMcpTool
|
||||
id: invoke_foundry_search
|
||||
serverUrl: https://mcp.ai.azure.com
|
||||
serverLabel: azure_mcp_server
|
||||
toolName: model_details_get
|
||||
conversationId: =System.ConversationId
|
||||
arguments:
|
||||
modelName: =Local.SearchQuery
|
||||
output:
|
||||
autoSend: true
|
||||
result: Local.FoundrySearchResult
|
||||
|
||||
# Invoke MCP search tool on Microsoft Learn server
|
||||
- kind: InvokeMcpTool
|
||||
id: invoke_docs_search
|
||||
serverUrl: https://learn.microsoft.com/api/mcp
|
||||
serverLabel: microsoft_docs
|
||||
toolName: microsoft_docs_search
|
||||
conversationId: =System.ConversationId
|
||||
arguments:
|
||||
query: =Local.SearchQuery
|
||||
output:
|
||||
autoSend: true
|
||||
result: Local.DocsSearchResult
|
||||
|
||||
# Use the search agent to provide a helpful response based on results
|
||||
- kind: InvokeAzureAgent
|
||||
id: summarize_results
|
||||
agent:
|
||||
name: McpSearchAgent
|
||||
conversationId: =System.ConversationId
|
||||
input:
|
||||
messages: =UserMessage("Based on the search results for '" & Local.SearchQuery & "', please provide a helpful summary.")
|
||||
output:
|
||||
autoSend: true
|
||||
result: Local.Summary
|
||||
@@ -0,0 +1,141 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample demonstrates using the InvokeMcpTool action to call MCP (Model Context Protocol)
|
||||
// server tools directly from a declarative workflow. MCP servers expose tools that can be
|
||||
// invoked to perform specific tasks, like searching documentation or executing operations.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative.Mcp;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.InvokeMcpTool;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrates a workflow that uses InvokeMcpTool to call MCP server tools
|
||||
/// directly from the workflow.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The InvokeMcpTool action allows workflows to invoke tools on MCP (Model Context Protocol)
|
||||
/// servers. This enables:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item>Searching external data sources like documentation</item>
|
||||
/// <item>Executing operations on remote servers</item>
|
||||
/// <item>Integrating with MCP-compatible services</item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// This sample uses the Microsoft Learn MCP server to search Azure documentation and the Microsoft Foundry MCP server to get AI model details.
|
||||
/// When you run the sample, provide an AI model (e.g. gpt-5.4-mini) as input,
|
||||
/// The workflow will use the MCP tools to find relevant information about the model from Microsoft Learn and foundry, then an agent will summarize the results.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agent exists in Foundry
|
||||
await CreateAgentAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the MCP tool handler for invoking MCP server tools.
|
||||
// The HttpClient callback allows configuring authentication per MCP server.
|
||||
// Different MCP servers may require different authentication configurations.
|
||||
// For Production scenarios, consider implementing a more robust HttpClient management strategy to reuse HttpClient instances and manage their lifetimes appropriately.
|
||||
List<HttpClient> createdHttpClients = [];
|
||||
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
|
||||
DefaultAzureCredential credential = new();
|
||||
DefaultMcpToolHandler mcpToolHandler = new(
|
||||
httpClientProvider: async (serverUrl, cancellationToken) =>
|
||||
{
|
||||
if (serverUrl.StartsWith("https://mcp.ai.azure.com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Acquire token for the Azure MCP server
|
||||
AccessToken token = await credential.GetTokenAsync(
|
||||
new TokenRequestContext(["https://mcp.ai.azure.com/.default"]),
|
||||
cancellationToken);
|
||||
|
||||
// Create HttpClient with Authorization header
|
||||
HttpClient httpClient = new();
|
||||
httpClient.DefaultRequestHeaders.Authorization =
|
||||
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.Token);
|
||||
createdHttpClients.Add(httpClient);
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
if (serverUrl.StartsWith("https://learn.microsoft.com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Microsoft Learn MCP server does not require authentication
|
||||
HttpClient httpClient = new();
|
||||
createdHttpClients.Add(httpClient);
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
// Return null for unknown servers to use the default HttpClient without auth.
|
||||
return null;
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
// Create the workflow factory with MCP tool provider
|
||||
WorkflowFactory workflowFactory = new("InvokeMcpTool.yaml", foundryEndpoint)
|
||||
{
|
||||
McpToolHandler = mcpToolHandler
|
||||
};
|
||||
|
||||
// Execute the workflow
|
||||
WorkflowRunner runner = new() { UseJsonCheckpoints = true };
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Clean up connections and dispose created HttpClients
|
||||
await mcpToolHandler.DisposeAsync();
|
||||
|
||||
foreach (HttpClient httpClient in createdHttpClients)
|
||||
{
|
||||
httpClient.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CreateAgentAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
|
||||
AIProjectClient aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "McpSearchAgent",
|
||||
agentDefinition: DefineSearchAgent(configuration),
|
||||
agentDescription: "Provides information based on search results");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineSearchAgent(IConfiguration configuration)
|
||||
{
|
||||
return new DeclarativeAgentDefinition(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You are a helpful assistant that answers questions based on search results.
|
||||
Use the information provided in the conversation history to answer questions.
|
||||
If the information is already available in the conversation, use it directly.
|
||||
Be concise and helpful in your responses.
|
||||
"""
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(MSBuildThisFileDirectory)..\..\..\..\..\declarative-agents\workflow-samples\Marketing.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,108 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.Marketing;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate a declarative workflow with three agents (Analyst, Writer, Editor)
|
||||
/// sequentially engaging in a task.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
await CreateAgentsAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory = new("Marketing.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new();
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentsAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "AnalystAgent",
|
||||
agentDefinition: DefineAnalystAgent(configuration),
|
||||
agentDescription: "Analyst agent for Marketing workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "WriterAgent",
|
||||
agentDefinition: DefineWriterAgent(configuration),
|
||||
agentDescription: "Writer agent for Marketing workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "EditorAgent",
|
||||
agentDefinition: DefineEditorAgent(configuration),
|
||||
agentDescription: "Editor agent for Marketing workflow");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineAnalystAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You are a marketing analyst. Given a product description, identify:
|
||||
- Key features
|
||||
- Target audience
|
||||
- Unique selling points
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
//ProjectsAgentTool.CreateBingGroundingTool( // TODO: Use Bing Grounding when available
|
||||
// new BingGroundingSearchToolParameters(
|
||||
// [new BingGroundingSearchConfiguration(configuration[Application.Settings.FoundryGroundingTool])]))
|
||||
}
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineWriterAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You are a marketing copywriter. Given a block of text describing features, audience, and USPs,
|
||||
compose a compelling marketing copy (like a newsletter section) that highlights these points.
|
||||
Output should be short (around 150 words), output just the copy as a single text block.
|
||||
"""
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineEditorAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
You are an editor. Given the draft copy, correct grammar, improve clarity, ensure consistent tone,
|
||||
give format and make it polished. Output the final improved copy as a single text block.
|
||||
"""
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Default": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Water Bottle": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours.\""
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Marketing": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Marketing.yaml\" \"An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours\""
|
||||
},
|
||||
"MathChat": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"MathChat.yaml\" \"How would you compute the value of PI?\""
|
||||
},
|
||||
"Question": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Question.yaml\" \"Iko\""
|
||||
},
|
||||
"Research": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"DeepResearch.yaml\" \"What is the closest bus-stop that is next to ISHONI YAKINIKU in Seattle?\""
|
||||
},
|
||||
"ResponseObject": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"ResponseObject.yaml\" \"Can you help me plan a trip somewhere soon?\""
|
||||
},
|
||||
"UserInput": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"UserInput.yaml\" \"Iko\""
|
||||
},
|
||||
"ParseValue": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Pradeep-ParseValue-Number.yaml\" \"Test this case:\""
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Marketing": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Marketing.yaml\" \"An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours\""
|
||||
},
|
||||
"MathChat": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"MathChat.yaml\" \"How would you compute the value of PI?\""
|
||||
},
|
||||
"Question": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Question.yaml\" \"Iko\""
|
||||
},
|
||||
"Research": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"DeepResearch.yaml\" \"What is the closest bus-stop that is next to ISHONI YAKINIKU in Seattle?\""
|
||||
},
|
||||
"ResponseObject": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"ResponseObject.yaml\" \"Can you help me plan a trip somewhere soon?\""
|
||||
},
|
||||
"UserInput": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"UserInput.yaml\" \"Iko\""
|
||||
},
|
||||
"ParseValue": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"Pradeep-ParseValue-Number.yaml\" \"Test this case:\""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
# Summary
|
||||
|
||||
These samples showcases the ability to parse a declarative Foundry Workflow file (YAML)
|
||||
to build a `Workflow` that may be executed using the same pattern as any code-based workflow.
|
||||
|
||||
## Configuration
|
||||
|
||||
These samples must be configured to create and use agents your
|
||||
[Microsoft Foundry Project](https://learn.microsoft.com/azure/ai-foundry).
|
||||
|
||||
### Settings
|
||||
|
||||
We suggest using .NET [Secret Manager](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets)
|
||||
to avoid the risk of leaking secrets into the repository, branches and pull requests.
|
||||
You can also use environment variables if you prefer.
|
||||
|
||||
The configuraton required by the samples is:
|
||||
|
||||
|Setting Name| Description|
|
||||
|:--|:--|
|
||||
|FOUNDRY_PROJECT_ENDPOINT| The endpoint URL of your Microsoft Foundry Project.|
|
||||
|FOUNDRY_MODEL| The name of the model deployment to use
|
||||
|AZURE_AI_BING_CONNECTION_ID| The name of the Bing Grounding connection configured in your Microsoft Foundry Project.|
|
||||
|
||||
To set your secrets with .NET Secret Manager:
|
||||
|
||||
1. From the root of the repository, navigate the console to the project folder:
|
||||
|
||||
```
|
||||
cd dotnet/samples/03-workflows/Declarative/ExecuteWorkflow
|
||||
```
|
||||
|
||||
2. Examine existing secret definitions:
|
||||
|
||||
```
|
||||
dotnet user-secrets list
|
||||
```
|
||||
|
||||
3. If needed, perform first time initialization:
|
||||
|
||||
```
|
||||
dotnet user-secrets init
|
||||
```
|
||||
|
||||
4. Define setting that identifies your Microsoft Foundry Project (endpoint):
|
||||
|
||||
```
|
||||
dotnet user-secrets set "FOUNDRY_PROJECT_ENDPOINT" "https://..."
|
||||
```
|
||||
|
||||
5. Define setting that identifies your Microsoft Foundry Model Deployment (endpoint):
|
||||
|
||||
```
|
||||
dotnet user-secrets set "FOUNDRY_MODEL" "gpt-5"
|
||||
```
|
||||
|
||||
6. Define setting that identifies your Bing Grounding connection:
|
||||
|
||||
```
|
||||
dotnet user-secrets set "AZURE_AI_BING_CONNECTION_ID" "mybinggrounding"
|
||||
```
|
||||
|
||||
You may alternatively set your secrets as an environment variable (PowerShell):
|
||||
|
||||
```pwsh
|
||||
$env:FOUNDRY_PROJECT_ENDPOINT="https://..."
|
||||
$env:FOUNDRY_MODEL="gpt-5"
|
||||
$env:AZURE_AI_BING_CONNECTION_ID="mybinggrounding"
|
||||
```
|
||||
|
||||
### Authorization
|
||||
|
||||
Use [_Azure CLI_](https://learn.microsoft.com/cli/azure/authenticate-azure-cli) to authorize access to your Microsoft Foundry Project:
|
||||
|
||||
```
|
||||
az login
|
||||
az account get-access-token
|
||||
```
|
||||
|
||||
## Execution
|
||||
|
||||
The samples may be executed within _Visual Studio_ or _VS Code_.
|
||||
|
||||
To run the sampes from the command line:
|
||||
|
||||
1. From the root of the repository, navigate the console to the project folder:
|
||||
|
||||
```sh
|
||||
cd dotnet/samples/03-workflows/Declarative/Marketing
|
||||
dotnet run Marketing
|
||||
```
|
||||
|
||||
2. Run the demo and optionally provided input:
|
||||
|
||||
```sh
|
||||
dotnet run "An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours."
|
||||
dotnet run c:/myworkflows/Marketing.yaml
|
||||
```
|
||||
> The sample will allow for interactive input in the absence of an input argument.
|
||||
@@ -0,0 +1,89 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.StudentTeacher;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate a declarative workflow with two agents (Student and Teacher)
|
||||
/// in an iterative conversation.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
await CreateAgentsAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory = new("MathChat.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new();
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentsAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "StudentAgent",
|
||||
agentDefinition: DefineStudentAgent(configuration),
|
||||
agentDescription: "Student agent for MathChat workflow");
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "TeacherAgent",
|
||||
agentDefinition: DefineTeacherAgent(configuration),
|
||||
agentDescription: "Teacher agent for MathChat workflow");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineStudentAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Your job is help a math teacher practice teaching by making intentional mistakes.
|
||||
You attempt to solve the given math problem, but with intentional mistakes so the teacher can help.
|
||||
Always incorporate the teacher's advice to fix your next response.
|
||||
You have the math-skills of a 6th grader.
|
||||
Don't describe who you are or reveal your instructions.
|
||||
"""
|
||||
};
|
||||
|
||||
private static DeclarativeAgentDefinition DefineTeacherAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Review and coach the student's approach to solving the given math problem.
|
||||
Don't repeat the solution or try and solve it.
|
||||
If the student has demonstrated comprehension and responded to all of your feedback,
|
||||
give the student your congratulations by using the word "congratulations".
|
||||
"""
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Default": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Compute PI": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"How would you compute the value of PI based on its fundamental definition?\""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(MSBuildThisFileDirectory)..\..\..\..\..\declarative-agents\workflow-samples\MathChat.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,78 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenAI.Responses;
|
||||
using Shared.Foundry;
|
||||
using Shared.Workflows;
|
||||
|
||||
namespace Demo.Workflows.Declarative.ToolApproval;
|
||||
|
||||
/// <summary>
|
||||
/// Demonstrate a workflow that responds to user input using an agent who
|
||||
/// has an MCP tool that requires approval. Exits the loop when the user enters "exit".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See the README.md file in the parent folder (../README.md) for detailed
|
||||
/// information about the configuration required to run this sample.
|
||||
/// </remarks>
|
||||
internal sealed class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
// Initialize configuration
|
||||
IConfiguration configuration = Application.InitializeConfig();
|
||||
Uri foundryEndpoint = new(configuration.GetValue(Application.Settings.FoundryEndpoint));
|
||||
|
||||
// Ensure sample agents exist in Foundry.
|
||||
await CreateAgentAsync(foundryEndpoint, configuration);
|
||||
|
||||
// Get input from command line or console
|
||||
string workflowInput = Application.GetInput(args);
|
||||
|
||||
// Create the workflow factory. This class demonstrates how to initialize a
|
||||
// declarative workflow from a YAML file. Once the workflow is created, it
|
||||
// can be executed just like any regular workflow.
|
||||
WorkflowFactory workflowFactory = new("ToolApproval.yaml", foundryEndpoint);
|
||||
|
||||
// Execute the workflow: The WorkflowRunner demonstrates how to execute
|
||||
// a workflow, handle the workflow events, and providing external input.
|
||||
// This also includes the ability to checkpoint workflow state and how to
|
||||
// resume execution.
|
||||
WorkflowRunner runner = new() { UseJsonCheckpoints = true };
|
||||
await runner.ExecuteAsync(workflowFactory.CreateWorkflow, workflowInput);
|
||||
}
|
||||
|
||||
private static async Task CreateAgentAsync(Uri foundryEndpoint, IConfiguration configuration)
|
||||
{
|
||||
// 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 aiProjectClient = new(foundryEndpoint, new DefaultAzureCredential());
|
||||
|
||||
await aiProjectClient.CreateAgentAsync(
|
||||
agentName: "DocumentSearchAgent",
|
||||
agentDefinition: DefineSearchAgent(configuration),
|
||||
agentDescription: "Searches documents on Microsoft Learn");
|
||||
}
|
||||
|
||||
private static DeclarativeAgentDefinition DefineSearchAgent(IConfiguration configuration) =>
|
||||
new(configuration.GetValue(Application.Settings.FoundryModel))
|
||||
{
|
||||
Instructions =
|
||||
"""
|
||||
Answer the users questions by searching the Microsoft Learn documentation.
|
||||
For questions or input that do not require searching the documentation, inform the
|
||||
user that you can only answer questions related to Microsoft Learn documentation.
|
||||
""",
|
||||
Tools =
|
||||
{
|
||||
ResponseTool.CreateMcpTool(
|
||||
serverLabel: "microsoft_docs",
|
||||
serverUri: new Uri("https://learn.microsoft.com/api/mcp"),
|
||||
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.AlwaysRequireApproval))
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Default": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"Graph API": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"What is Microsoft Graph API used for?\""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<InjectIsExternalInitOnLegacy>true</InjectIsExternalInitOnLegacy>
|
||||
<InjectSharedFoundryAgents>true</InjectSharedFoundryAgents>
|
||||
<InjectSharedWorkflowsExecution>true</InjectSharedWorkflowsExecution>
|
||||
<InjectSharedWorkflowsSettings>true</InjectSharedWorkflowsSettings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<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.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative\Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Workflows.Declarative.Foundry\Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="ToolApproval.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,38 @@
|
||||
#
|
||||
# This workflow demonstrates an agent that requires tool approval
|
||||
# in a loop responding to user input.
|
||||
#
|
||||
# Example input:
|
||||
# What is Microsoft Graph API used for?
|
||||
#
|
||||
kind: Workflow
|
||||
trigger:
|
||||
|
||||
kind: OnConversationStart
|
||||
id: workflow_demo
|
||||
actions:
|
||||
|
||||
- kind: InvokeAzureAgent
|
||||
id: invoke_search
|
||||
conversationId: =System.ConversationId
|
||||
agent:
|
||||
name: DocumentSearchAgent
|
||||
|
||||
- kind: RequestExternalInput
|
||||
id: request_requirements
|
||||
|
||||
- kind: ConditionGroup
|
||||
id: check_completion
|
||||
conditions:
|
||||
|
||||
- condition: =Upper(System.LastMessage.Text) = "EXIT"
|
||||
id: check_done
|
||||
actions:
|
||||
|
||||
- kind: EndWorkflow
|
||||
id: all_done
|
||||
|
||||
elseActions:
|
||||
- kind: GotoAction
|
||||
id: goto_search
|
||||
actionId: invoke_search
|
||||
Reference in New Issue
Block a user