From 0ede847a9a7406fee612b1efe1b9a89999e1cc86 Mon Sep 17 00:00:00 2001 From: Manvir Kaur <67894494+manvkaur@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:35:48 -0800 Subject: [PATCH 1/4] Migrate large payload fan-out sample to .NET 10 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../LargePayloadFanOutFanIn.csproj | 12 ++++--- .../dotnet/LargePayloadFanOutFanIn/Program.cs | 23 +++++++++--- .../dotnet/LargePayloadFanOutFanIn/README.md | 35 ++++++++++++------- .../dotnet/LargePayloadFanOutFanIn/host.json | 16 +++------ .../infra/app/durable-function.bicep | 3 +- .../LargePayloadFanOutFanIn/infra/main.bicep | 2 +- 6 files changed, 55 insertions(+), 36 deletions(-) diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadFanOutFanIn.csproj b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadFanOutFanIn.csproj index 8dce54dc..158f441b 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadFanOutFanIn.csproj +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadFanOutFanIn.csproj @@ -1,6 +1,6 @@ - net8.0 + net10.0 v4 Exe enable @@ -9,13 +9,15 @@ - + - - - + + + + + diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs index 4b07a32c..064503d1 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs @@ -1,13 +1,28 @@ -using Microsoft.Azure.Functions.Worker; +using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Azure.Functions.Worker.OpenTelemetry; +using Microsoft.Extensions.Azure; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; var host = new HostBuilder() .ConfigureFunctionsWebApplication() - .ConfigureServices(services => + .ConfigureServices((context, services) => { - services.AddApplicationInsightsTelemetryWorkerService(); - services.ConfigureFunctionsApplicationInsights(); + string? connectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]; + if (!string.IsNullOrWhiteSpace(connectionString)) + { + services.AddAzureClientsCore(); + services.AddOptions() + .Configure((options, factory) => + { + options.ConnectionString = connectionString; + options.Credential = factory.CreateTokenCredential( + context.Configuration.GetSection("AzureMonitorExporter")); + }); + services.AddOpenTelemetry() + .UseFunctionsWorkerDefaults() + .UseAzureMonitorExporter(); + } }) .Build(); diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md index 3e5e407e..83d72c91 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md @@ -24,7 +24,7 @@ If you want the smallest possible example, start with the sibling [LargePayload] The flow is intentionally parallel: -1. An HTTP trigger starts an orchestration with a payload size larger than 1 MB. +1. An HTTP trigger starts an orchestration with a small request specifying the activity count and payload size. 2. The orchestrator fans out to multiple activities. 3. Each activity generates a payload larger than 1 MB and returns it to the orchestrator. 4. The orchestrator fans in and returns a small summary proving every activity payload survived the round-trip. @@ -42,7 +42,7 @@ The sample enables these settings in `host.json`: "connectionStringName": "DTS_CONNECTION_STRING", "payloadStorageEnabled": true, "payloadStorageThresholdBytes": 262144, - "payloadStorageMaxPayloadBytes": 15728640 + "payloadStorageMaxSizeBytes": 15728640 }, "hubName": "%TASKHUB_NAME%" } @@ -59,9 +59,9 @@ The sample uses **three deterministic, low-compressibility 1.5 MiB activity payl ### Maximum payload size -`payloadStorageThresholdBytes` controls *when* a payload is externalized. A separate setting, `payloadStorageMaxPayloadBytes`, controls the **largest single serialized UTF-8 payload** the runtime will externalize: +`payloadStorageThresholdBytes` controls *when* a payload is externalized. A separate setting, `payloadStorageMaxSizeBytes`, controls the **largest single serialized UTF-8 payload** the runtime will externalize: -- If you don't set `payloadStorageMaxPayloadBytes`, the default maximum is **10 MB (10,485,760 bytes, shown as 10,240 KB in the error message)**. +- If you don't set `payloadStorageMaxSizeBytes`, the default maximum is **10 MB (10,485,760 bytes, shown as 10,240 KB in the error message)**. - The cap applies to each **single** externalized payload (here, each activity's payload), not the combined total across all activities. - An activity output whose serialized payload exceeds the maximum fails when the runtime tries to externalize that result. The orchestration has already been scheduled: its input contains only the activity count and requested size, and each activity generates its payload later. The error is: @@ -69,22 +69,22 @@ The sample uses **three deterministic, low-compressibility 1.5 MiB activity payl Payload size 10742 KB exceeds the configured maximum of 10240 KB. Reduce the payload size or increase the max payload size limit. ``` -- This is a **configurable limit, not a hard product limit**. To allow larger payloads, raise `payloadStorageMaxPayloadBytes` in `host.json`. This sample sets it to `15728640` (15 MiB) per serialized payload, including JSON serialization overhead. +- This is a **configurable limit, not a hard product limit**. To allow larger payloads, raise `payloadStorageMaxSizeBytes` in `host.json`. This sample sets it to `15728640` (15 MiB) per serialized payload, including JSON serialization overhead. -#### `PAYLOAD_SIZE_BYTES` is not `payloadStorageMaxPayloadBytes` +#### `PAYLOAD_SIZE_BYTES` is not `payloadStorageMaxSizeBytes` These two settings are easy to confuse but do completely different things: | Setting | Where it lives | What it controls | |---|---|---| | `PAYLOAD_SIZE_BYTES` | app setting / `local.settings.json` | How many bytes of test data **each activity generates** for its demo payload. | -| `payloadStorageMaxPayloadBytes` | `host.json` | The **maximum** size of any single payload the runtime will externalize. Larger payloads fail fast. | +| `payloadStorageMaxSizeBytes` | `host.json` | The **maximum** size of any single payload the runtime will externalize. Larger payloads fail fast. | -If you raise `PAYLOAD_SIZE_BYTES` above `payloadStorageMaxPayloadBytes` (for example `PAYLOAD_SIZE_BYTES=11000000` against the default 10 MB cap), the run fails **by design** with the error above. Set the cap above the per-activity generated data size, leaving room for JSON string quotes. Setting the two values equal can still exceed the cap after serialization. +If you raise `PAYLOAD_SIZE_BYTES` above `payloadStorageMaxSizeBytes` (for example `PAYLOAD_SIZE_BYTES=11000000` against the default 10 MB cap), the run fails **by design** with the error above. Set the cap above the per-activity generated data size, leaving room for JSON string quotes. Setting the two values equal can still exceed the cap after serialization. ## Prerequisites -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) +- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) - [Azure Functions Core Tools v4](https://learn.microsoft.com/azure/azure-functions/functions-run-local) - [Docker](https://www.docker.com/products/docker-desktop/) - [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) @@ -160,7 +160,7 @@ The extension stores payload blobs with gzip content encoding, so Azure shows th | `DTS_CONNECTION_STRING` | DTS emulator or Azure connection string | `Endpoint=http://localhost:8080;Authentication=None` | | `TASKHUB_NAME` | Task hub name | `default` | | `AzureWebJobsStorage` | Storage for Functions host state and payload blobs | `UseDevelopmentStorage=true` locally | -| `PAYLOAD_SIZE_BYTES` | Size of the test payload each activity generates. Keep it below `payloadStorageMaxPayloadBytes` (15 MiB in this sample), leaving room for JSON serialization overhead. | `1572864` | +| `PAYLOAD_SIZE_BYTES` | Size of the test payload each activity generates. Keep it below `payloadStorageMaxSizeBytes` (15 MiB in this sample), leaving room for JSON serialization overhead. | `1572864` | | `ACTIVITY_COUNT` | Number of parallel activity invocations | `3` | ## Deploy to Azure with AZD @@ -183,9 +183,10 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p The deployment provisions: - an Azure Function App - - a storage account used for `AzureWebJobsStorage` + - a storage account used for `AzureWebJobsStorage`, with a blob private endpoint - a Durable Task Scheduler resource and task hub - - a user-assigned managed identity with the required DTS and storage permissions + - Application Insights and Log Analytics + - a user-assigned managed identity with the required DTS, storage, and monitoring permissions 3. Load the environment values: @@ -199,7 +200,7 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p curl -X POST "https://${AZURE_FUNCTION_NAME}.azurewebsites.net/api/StartLargePayload" ``` -5. Verify payload blobs in Azure storage: +5. Verify payload blobs in Azure storage. The storage firewall denies public access by default; the deployment script allows the deploying machine's IP so this command can run from there: ```bash az storage blob list \ @@ -211,6 +212,14 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p 6. Open the DTS dashboard URL in the Azure portal to inspect the orchestration history. +## Telemetry + +The Functions host uses OpenTelemetry (`telemetryMode` in `host.json`). + +When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker registers OpenTelemetry and exports to Azure Monitor. The exporter authenticates with the app's managed identity through the dedicated `AzureMonitorExporter` settings (`AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`), so Application Insights local authentication can stay disabled. Without that connection string, as in local emulator runs, the worker does not export. + +In Application Insights, inspect `requests`, `dependencies`, and `traces` for exported telemetry. Payload contents are not logged. + ## Files to look at - `LargePayloadOrchestration.cs` — HTTP starter, fan-out/fan-in orchestrator, and payload-generating activity diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/host.json b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/host.json index 480e57f6..b66ffd37 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/host.json +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/host.json @@ -1,18 +1,10 @@ { "version": "2.0", + "telemetryMode": "OpenTelemetry", "logging": { - "applicationInsights": { - "samplingSettings": { - "isEnabled": true, - "excludedTypes": "Request" - }, - "enableLiveMetricsFilters": true, - "logLevel": { - "Host.Triggers.DurableTask": "Information" - } - }, "logLevel": { - "Function": "Information" + "Function": "Information", + "Host.Triggers.DurableTask": "Information" } }, "extensions": { @@ -22,7 +14,7 @@ "connectionStringName": "DTS_CONNECTION_STRING", "payloadStorageEnabled": true, "payloadStorageThresholdBytes": 262144, - "payloadStorageMaxPayloadBytes": 15728640 + "payloadStorageMaxSizeBytes": 15728640 }, "hubName": "%TASKHUB_NAME%" } diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/app/durable-function.bicep b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/app/durable-function.bicep index 1de57197..13fd1345 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/app/durable-function.bicep +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/app/durable-function.bicep @@ -31,9 +31,10 @@ module durableFunction '../core/host/functions.bicep' = { AzureWebJobsStorage__clientId : identityClientId AzureWebJobsStorage__credential : 'managedidentity' APPLICATIONINSIGHTS_AUTHENTICATION_STRING: applicationInsightsIdentity + AzureMonitorExporter__credential: 'managedidentity' + AzureMonitorExporter__clientId: identityClientId DTS_CONNECTION_STRING: 'Endpoint=${dtsURL};Authentication=ManagedIdentity;ClientID=${identityClientId}' TASKHUB_NAME: taskHubName - AZURE_CLIENT_ID: identityClientId }) applicationInsightsName: applicationInsightsName appServicePlanId: appServicePlanId diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/main.bicep b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/main.bicep index 7cccab77..b210c4d6 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/main.bicep +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/main.bicep @@ -118,7 +118,7 @@ module durableFunction './app/durable-function.bicep' = { applicationInsightsName: monitoring.outputs.applicationInsightsName appServicePlanId: appServicePlan.outputs.id runtimeName: 'dotnet-isolated' - runtimeVersion: '8.0' + runtimeVersion: '10.0' storageAccountName: storage.outputs.name deploymentStorageContainerName: deploymentStorageContainerName identityId: durableFunctionUserAssignedIdentity.outputs.identityId From 99909604baeb99770ed180465129fb51e4fbef33 Mon Sep 17 00:00:00 2001 From: Manvir Kaur <67894494+manvkaur@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:49:36 -0800 Subject: [PATCH 2/4] Migrate Durable Functions .NET samples to .NET 10 and harden them - Migrate AiAgentTravelPlanOrchestrator, DistributedTracing, LargePayload and Saga to net10.0 with current stable packages and OpenTelemetry. - Require function keys on HTTP triggers for the four non-AI samples. - Validate large payload content, not just length; fan in per-child summaries instead of materializing all payloads. - Document payload blob retention. - Replace the AI sample's hub-based Foundry template with an AIServices account + project, using the project endpoint and Azure AI User role (from #448). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Functions/TravelPlannerOrchestrator.cs | 28 ++- .../AiAgentTravelPlanOrchestrator/Program.cs | 23 +- .../AiAgentTravelPlanOrchestrator/README.md | 62 ++++-- .../TravelPlannerFunctions.csproj | 17 +- .../AiAgentTravelPlanOrchestrator/host.json | 14 +- .../infra/agent/ai-foundry-access.bicep | 28 +++ .../infra/agent/ai-foundry.bicep | 104 +++++++++ .../agent/ai-search-role-assignments.bicep | 39 ---- .../agent/ai-service-role-assignments.bicep | 58 ----- .../infra/agent/standard-ai-hub.bicep | 111 ---------- .../infra/agent/standard-ai-project.bicep | 78 ------- .../agent/standard-dependent-resources.bicep | 192 ---------------- .../infra/app/api.bicep | 2 + .../infra/app/vnet.bicep | 4 +- .../infra/core/host/functions-app.bicep | 4 +- .../infra/main.bicep | 206 +++++------------- .../infra/main.parameters.json | 3 + .../DistributedTracing.csproj | 17 +- .../dotnet/DistributedTracing/Functions.cs | 2 +- .../dotnet/DistributedTracing/Program.cs | 26 ++- .../dotnet/DistributedTracing/README.md | 27 ++- .../dotnet/DistributedTracing/host.json | 7 +- .../dotnet/LargePayload/LargePayload.csproj | 12 +- .../LargePayload/LargePayloadOrchestration.cs | 25 ++- .../dotnet/LargePayload/Program.cs | 23 +- .../dotnet/LargePayload/README.md | 55 +++-- .../dotnet/LargePayload/host.json | 16 +- .../infra/app/durable-function.bicep | 3 +- .../dotnet/LargePayload/infra/main.bicep | 2 +- .../LargePayloadOrchestration.cs | 66 ++++-- .../dotnet/LargePayloadFanOutFanIn/README.md | 40 +++- .../core/host/functions-flexconsumption.bicep | 4 +- .../dotnet/Saga/DurableFunctionsSaga.csproj | 18 +- .../dotnet/Saga/Functions/HttpTriggers.cs | 6 +- .../durable-functions/dotnet/Saga/Program.cs | 21 ++ .../durable-functions/dotnet/Saga/README.md | 24 +- .../durable-functions/dotnet/Saga/host.json | 1 + .../durable-functions/dotnet/Saga/test.http | 7 + 38 files changed, 602 insertions(+), 773 deletions(-) create mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep create mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep delete mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep delete mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep delete mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep delete mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep delete mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs index 3d8a2d66..ceb63ade 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs @@ -9,6 +9,9 @@ namespace TravelPlannerFunctions.Functions; public class TravelPlannerOrchestrator { + // Durable custom status limit is 16 KB (UTF-16); keep headroom for serializer differences. + private const int MaxCustomStatusBytes = 15 * 1024; + private readonly ILogger _logger; public TravelPlannerOrchestrator(ILoggerFactory loggerFactory) @@ -153,12 +156,33 @@ public async Task RunTravelPlannerOrchestration( } }; - // The custom status has a max size of 16KB. + // The custom status has a max size of 16KB (UTF-16). Detailed agent output can exceed it, + // so fall back to a summary; the full plan remains available via documentUrl. var waitingStatusSize = Encoding.Unicode.GetByteCount(JsonSerializer.Serialize(waitingStatus)); logger.LogInformation("Waiting status size: {Size} bytes", waitingStatusSize); - context.SetCustomStatus(waitingStatus); + if (waitingStatusSize <= MaxCustomStatusBytes) + { + context.SetCustomStatus(waitingStatus); + } + else + { + logger.LogWarning("Waiting status size {Size} bytes exceeds limit; sending summary status instead", waitingStatusSize); + context.SetCustomStatus(new { + waitingStatus.step, + waitingStatus.message, + waitingStatus.progress, + waitingStatus.destination, + waitingStatus.documentUrl, + travelPlan = new { + waitingStatus.travelPlan.destination, + waitingStatus.travelPlan.dates, + waitingStatus.travelPlan.cost, + waitingStatus.travelPlan.days + } + }); + } approvalResponse = await context.WaitForExternalEvent( "ApprovalEvent", diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs index 7f5dd6e3..0c058aea 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs @@ -1,4 +1,5 @@ -using Microsoft.Azure.Functions.Worker; +using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Azure.Functions.Worker.OpenTelemetry; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; @@ -6,14 +7,26 @@ using Microsoft.Extensions.Logging; using Azure.Identity; using TravelPlannerFunctions.Services; -using Azure.AI.Projects; var host = new HostBuilder() .ConfigureFunctionsWebApplication() - .ConfigureServices(services => + .ConfigureServices((context, services) => { - services.AddApplicationInsightsTelemetryWorkerService(); - services.ConfigureFunctionsApplicationInsights(); + string? connectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]; + if (!string.IsNullOrWhiteSpace(connectionString)) + { + services.AddAzureClientsCore(); + services.AddOptions() + .Configure((options, factory) => + { + options.ConnectionString = connectionString; + options.Credential = factory.CreateTokenCredential( + context.Configuration.GetSection("AzureMonitorExporter")); + }); + services.AddOpenTelemetry() + .UseFunctionsWorkerDefaults() + .UseAzureMonitorExporter(); + } services.AddLogging(); services.AddSingleton((serviceProvider) => diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md index 052abfc3..c52734b8 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md @@ -66,6 +66,12 @@ The complete travel plan is saved to Azure Blob Storage, and a document URL is g The travel plan is presented to the user for approval via the frontend interface. +### Travel-plan blob retention + +The sample writes documents to the private `travel-plans` container and configures no automatic expiry or cleanup job. Treat the returned blob URL as a location, not a public download link or a retention guarantee. Reading it still requires authorized storage access. + +Retain documents throughout the approval wait (up to seven days), booking/recovery, and the period during which users need to retrieve the plan or retained orchestration output. For production, choose an explicit business/privacy retention period, then delete eligible documents after those requirements end; coordinate this with durable history retention so saved URLs do not unexpectedly point to deleted plans. A lifecycle rule based only on blob age can delete a plan while approval or recovery is still pending. Account for soft-delete and version retention, which can retain data and incur charges after deletion. Deleting the dedicated sample environment removes its storage; do not delete a shared storage account to clean up travel plans. + ### Step 8: Booking Process (Conditional) If approved, the orchestrator proceeds with the booking process. If rejected, it can either terminate or restart with modified preferences. @@ -77,7 +83,7 @@ Upon successful booking, the user receives a final confirmation with all travel ## Prerequisites - Docker -- .NET 8 SDK +- .NET 10 SDK - Azure Functions Core Tools v4 - Node.js 22.12+ and npm (required by the frontend's Azure Storage and Vite dependencies) - Azure Developer CLI (azd) @@ -85,7 +91,11 @@ Upon successful booking, the user receives a final confirmation with all travel - Azure Functions resource - Azure Storage Account - Azure Durable Task resource - - Azure AI Projects with configured agents + - Microsoft Foundry project with configured agents + +## Telemetry + +The Functions host uses OpenTelemetry. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports to Azure Monitor using the app's managed identity through `AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`. Without that connection string, the worker does not export. `AZURE_CLIENT_ID` is still required by the agent and storage clients. ## Setting Up Locally @@ -110,9 +120,9 @@ Create a `local.settings.json` file in the root directory with the following con "TASKHUB_NAME": "default", "AZURE_TENANT_ID": "", "AZURE_CLIENT_ID": "", - "DESTINATION_RECOMMENDER_CONNECTION": "", - "ITINERARY_PLANNER_CONNECTION": "", - "LOCAL_RECOMMENDATIONS_CONNECTION": "", + "DESTINATION_RECOMMENDER_CONNECTION": "", + "ITINERARY_PLANNER_CONNECTION": "", + "LOCAL_RECOMMENDATIONS_CONNECTION": "", "DESTINATION_RECOMMENDER_AGENT_ID": "", "ITINERARY_PLANNER_AGENT_ID": "", "LOCAL_RECOMMENDATIONS_AGENT_ID": "" @@ -125,7 +135,7 @@ Create a `local.settings.json` file in the root directory with the following con } ``` -Replace the placeholder values with your actual connection strings and agent IDs. +Replace the placeholder values with your Microsoft Foundry project endpoint and agent IDs. The `*_CONNECTION` settings must be the project endpoint URL, for example `https://.services.ai.azure.com/api/projects/`. Hub-based project connection strings (`.api.azureml.ms;...`) aren't supported by the `Azure.AI.Projects` 2.x SDK used by this sample. ### 3. Set Up Azure Storage Emulator @@ -216,14 +226,24 @@ azd up This command will: -- Create all required Azure resources as defined in your infrastructure files +- Create all required Azure resources as defined in your infrastructure files, including a Microsoft Foundry resource, a Foundry project, and a `gpt-5-mini` model deployment - Build the backend Azure Functions - Build and deploy the frontend Vite React application -- Configure all connections between components +- Configure the function app with the Foundry project endpoint and grant its managed identity the **Foundry User** role (formerly **Azure AI User**) on the Foundry resource + +> [!NOTE] +> Choose `eastus2` or `swedencentral` as the location. Both regions support Durable Task Scheduler and the `gpt-5-mini` `GlobalStandard` deployment. To use a different model, set the `modelName`, `modelVersion`, `modelSkuName`, and `modelCapacity` parameters in `infra/main.bicep`. + +> [!IMPORTANT] +> By default, the Foundry resource allows public network access so that the function app can reach it. The template doesn't create a private endpoint for Foundry. To block public access, run `azd env set AI_PUBLIC_NETWORK_ACCESS Disabled` before `azd up`, and provide your own private endpoint and virtual network integration so the function app can still reach the Foundry project. +> +> The default `skipVnet=true` deployment is not a private deployment. Private Function App ingress also requires a private endpoint. The Static Web App linked backend configures Function App authentication; direct API calls must satisfy that authentication and may return 401 without it. ### 4. Configure AI Agents -After deployment, you'll need to set up the three AI agents in Azure AI Projects: +After deployment, create the three agents in the Foundry project. You can create them in the [Foundry portal](https://ai.azure.com) or by calling the Agent Service REST API with the deployed model. The deploying user is granted the **Foundry User** role on the Foundry resource, which is required to create agents. Role assignments can take a few minutes to take effect. + +Use the following instructions for each agent: #### Destination Recommender Agent @@ -256,17 +276,31 @@ Focus on both popular and hidden gem attractions, dining options across differen price ranges, and practical local tips that tourists wouldn't typically know. ``` +For example, the following PowerShell script creates the destination recommender agent and returns its ID. Repeat it for the other two agents with their names and instructions. + +```PowerShell +$projectEndpoint = azd env get-value PROJECT_ENDPOINT +$model = azd env get-value AI_MODEL_DEPLOYMENT_NAME +$token = az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv +$body = @{ + name = "destination-recommender" + model = $model + instructions = "You are a destination recommendation expert that helps travelers find ideal vacation spots based on their preferences, budget, and travel dates." +} | ConvertTo-Json + +$agent = Invoke-RestMethod -Method Post -Uri "$projectEndpoint/assistants?api-version=2025-05-01" ` + -Headers @{ Authorization = "Bearer $token" } -ContentType "application/json" -Body $body +$agent.id +``` + ### 5. Update Configuration -Update your application settings with the proper agent connection strings and IDs: +Set the agent IDs (they start with `asst_`) and reprovision to update the function app settings. The `*_CONNECTION` settings are already set to the Foundry project endpoint by the template. ```bash azd env set DESTINATION_RECOMMENDER_AGENT_ID "your-agent-id" azd env set ITINERARY_PLANNER_AGENT_ID "your-agent-id" azd env set LOCAL_RECOMMENDATIONS_AGENT_ID "your-agent-id" -azd env set DESTINATION_RECOMMENDER_CONNECTION "your-connection-string" -azd env set ITINERARY_PLANNER_CONNECTION "your-connection-string" -azd env set LOCAL_RECOMMENDATIONS_CONNECTION "your-connection-string" # Apply these changes to your Azure resources azd provision @@ -310,7 +344,7 @@ azd down --purge - [Azure Durable Task Scheduler](https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-durable-task-scheduler?pivots=csharp) - [Azure Durable Functions Documentation](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-overview) -- [Azure AI Projects Documentation](https://learn.microsoft.com/en-us/azure/ai-studio/how-to/projects-sdk-overview) +- [Microsoft Foundry Agent Service Documentation](https://learn.microsoft.com/azure/ai-foundry/agents/overview) - [Azure Functions Isolated Process Model](https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide) - [Azure Developer CLI Documentation](https://learn.microsoft.com/en-us/azure/developer/azure-developer-cli/) - [Azurite Emulator](https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite?tabs=visual-studio%2Cblob-storage) diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj index bef43601..d9b21d1e 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj @@ -1,6 +1,6 @@ - net8.0 + net10.0 v4 Exe enable @@ -12,19 +12,20 @@ - - + + - + - - - + + + + - + diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json index 0b2b93eb..05513dd6 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json @@ -1,18 +1,10 @@ { "version": "2.0", + "telemetryMode": "OpenTelemetry", "logging": { - "applicationInsights": { - "samplingSettings": { - "isEnabled": true, - "excludedTypes": "Request" - }, - "enableLiveMetricsFilters": true, - "logLevel": { - "Host.Triggers.DurableTask": "Information" - } - }, "logLevel": { - "Function": "Information" + "Function": "Information", + "Host.Triggers.DurableTask": "Information" } }, "extensions": { diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep new file mode 100644 index 00000000..f36bde66 --- /dev/null +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep @@ -0,0 +1,28 @@ +// Assigns a role on the Foundry resource (AIServices account) to a principal. + +@description('Name of the Foundry resource (AIServices account)') +param aiFoundryName string + +@description('Role definition ID to assign') +param roleDefinitionID string + +@description('Principal ID to assign the role to') +param principalID string + +@description('Type of the principal') +@allowed(['User', 'ServicePrincipal', 'Group']) +param principalType string = 'ServicePrincipal' + +resource aiFoundry 'Microsoft.CognitiveServices/accounts@2025-06-01' existing = { + name: aiFoundryName +} + +resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + name: guid(aiFoundry.id, principalID, roleDefinitionID) + scope: aiFoundry + properties: { + roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionID) + principalId: principalID + principalType: principalType + } +} diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep new file mode 100644 index 00000000..1e838300 --- /dev/null +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep @@ -0,0 +1,104 @@ +// Creates a Microsoft Foundry resource (AIServices account), a Foundry project, and a model deployment. +// The project endpoint output is the value expected by Azure.AI.Projects 2.x (AIProjectClient). + +@description('Azure region of the Foundry resource and model deployment') +param location string + +@description('Tags to add to the resources') +param tags object = {} + +@description('Name of the Foundry resource (AIServices account). Also used as the custom subdomain.') +param aiFoundryName string + +@description('Name of the Foundry project') +param aiProjectName string + +@description('Display name of the Foundry project') +param aiProjectFriendlyName string = aiProjectName + +@description('Description of the Foundry project') +param aiProjectDescription string = '' + +@description('Model name for deployment') +param modelName string + +@description('Model format for deployment') +param modelFormat string + +@description('Model version for deployment') +param modelVersion string + +@description('Model deployment SKU name') +param modelSkuName string + +@description('Model deployment capacity') +param modelCapacity int + +@description('Whether the Foundry resource accepts traffic from public networks') +@allowed(['Enabled', 'Disabled']) +param publicNetworkAccess string = 'Enabled' + +resource aiFoundry 'Microsoft.CognitiveServices/accounts@2025-06-01' = { + name: aiFoundryName + location: location + tags: tags + kind: 'AIServices' + sku: { + name: 'S0' + } + identity: { + type: 'SystemAssigned' + } + properties: { + allowProjectManagement: true + customSubDomainName: toLower(aiFoundryName) + // The app authenticates with Microsoft Entra ID (managed identity), so keys are not needed. + disableLocalAuth: true + publicNetworkAccess: publicNetworkAccess + networkAcls: { + defaultAction: publicNetworkAccess == 'Enabled' ? 'Allow' : 'Deny' + } + } +} + +resource aiProject 'Microsoft.CognitiveServices/accounts/projects@2025-06-01' = { + parent: aiFoundry + name: aiProjectName + location: location + tags: tags + identity: { + type: 'SystemAssigned' + } + properties: { + displayName: aiProjectFriendlyName + description: aiProjectDescription + } +} + +resource modelDeployment 'Microsoft.CognitiveServices/accounts/deployments@2025-06-01' = { + parent: aiFoundry + name: modelName + sku: { + name: modelSkuName + capacity: modelCapacity + } + properties: { + model: { + name: modelName + format: modelFormat + version: modelVersion + } + } + dependsOn: [ + aiProject + ] +} + +output aiFoundryName string = aiFoundry.name +output aiFoundryId string = aiFoundry.id +output aiProjectName string = aiProject.name +output aiProjectResourceId string = aiProject.id +output aiProjectPrincipalId string = aiProject.identity.principalId +output modelDeploymentName string = modelDeployment.name +// Format: https://.services.ai.azure.com/api/projects/ +output projectEndpoint string = aiProject.properties.endpoints['AI Foundry API'] diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep deleted file mode 100644 index 4efab91a..00000000 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep +++ /dev/null @@ -1,39 +0,0 @@ -param aiSearchName string -param aiProjectPrincipalId string -param aiProjectId string - -resource searchService 'Microsoft.Search/searchServices@2024-06-01-preview' existing = { - name: aiSearchName - scope: resourceGroup() -} - -// search roles -resource searchIndexDataContributorRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { - name: '8ebe5a00-799e-43f5-93ac-243d3dce84a7' - scope: resourceGroup() -} - -resource searchIndexDataContributorAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { - scope: searchService - name: guid(aiProjectId, searchIndexDataContributorRole.id, searchService.id) - properties: { - principalId: aiProjectPrincipalId - roleDefinitionId: searchIndexDataContributorRole.id - principalType: 'ServicePrincipal' - } -} - -resource searchServiceContributorRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { - name: '7ca78c08-252a-4471-8644-bb5ff32d4ba0' - scope: resourceGroup() -} - -resource searchServiceContributorRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { - scope: searchService - name: guid(aiProjectId, searchServiceContributorRole.id, searchService.id) - properties: { - principalId: aiProjectPrincipalId - roleDefinitionId: searchServiceContributorRole.id - principalType: 'ServicePrincipal' - } -} diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep deleted file mode 100644 index 8cbbdf83..00000000 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep +++ /dev/null @@ -1,58 +0,0 @@ -// Assigns the necessary roles to the AI project - -param aiServicesName string -param aiProjectPrincipalId string -param aiProjectId string - -resource aiServices 'Microsoft.CognitiveServices/accounts@2024-06-01-preview' existing = { - name: aiServicesName - scope: resourceGroup() -} - -resource cognitiveServicesContributorRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { - name: '25fbc0a9-bd7c-42a3-aa1a-3b75d497ee68' - scope: resourceGroup() - -} - -resource cognitiveServicesContributorAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01'= { - scope: aiServices - name: guid(aiServices.id, cognitiveServicesContributorRole.id, aiProjectId) - properties: { - principalId: aiProjectPrincipalId - roleDefinitionId: cognitiveServicesContributorRole.id - principalType: 'ServicePrincipal' - } -} - -var cognitiveServicesOpenAIUserRoleId = '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' -resource cognitiveServicesOpenAIUserRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { - name: cognitiveServicesOpenAIUserRoleId - scope: resourceGroup() -} - -resource cognitiveServicesOpenAIUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { - scope: aiServices - name: guid(aiProjectId, cognitiveServicesOpenAIUserRole.id, aiServices.id) - properties: { - principalId: aiProjectPrincipalId - roleDefinitionId: cognitiveServicesOpenAIUserRole.id - principalType: 'ServicePrincipal' - } -} - -var cognitiveServiceServicesUserRoleId = 'a97b65f3-24c7-4388-baec-2e87135dc908' -resource cognitiveServicesUserRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { - name: cognitiveServiceServicesUserRoleId - scope: resourceGroup() -} - -resource cognitiveServicesUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { - scope: aiServices - name: guid(aiProjectId, cognitiveServicesUserRole.id, aiServices.id) - properties: { - principalId: aiProjectPrincipalId - roleDefinitionId: cognitiveServicesUserRole.id - principalType: 'ServicePrincipal' - } -} diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep deleted file mode 100644 index 3c83e13e..00000000 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep +++ /dev/null @@ -1,111 +0,0 @@ -@description('Azure region of the deployment') -param location string - -@description('Tags to add to the resources') -param tags object - -@description('AI hub name') -param aiHubName string - -@description('AI hub display name') -param aiHubFriendlyName string = aiHubName - -@description('AI hub description') -param aiHubDescription string - -@description('Resource ID of the key vault resource for storing connection strings') -param keyVaultId string - -@description('Resource ID of the storage account resource for storing experimentation outputs') -param storageAccountId string - -@description('Resource ID of the AI Services resource') -param aiServicesId string -@description('Resource ID of the AI Services endpoint') -param aiServicesTarget string -@description('Name AI Services resource') -param aiServicesName string - - -@description('Name AI Search resource') -param aiSearchName string -@description('Resource ID of the AI Search resource') -param aiSearchId string -@description('Name for capabilityHost.') -param capabilityHostName string = 'caphost1' - -var acsConnectionName = '${aiHubName}-connection-AISearch' - -var aoaiConnection = '${aiHubName}-connection-AIServices_aoai' - -resource aiServices 'Microsoft.CognitiveServices/accounts@2023-05-01' existing = { - name: aiServicesName - scope: resourceGroup() -} - -resource searchService 'Microsoft.Search/searchServices@2023-11-01' existing = { - name: aiSearchName - scope: resourceGroup() -} - -resource aiHub 'Microsoft.MachineLearningServices/workspaces@2024-07-01-preview' = { - name: aiHubName - location: location - tags: tags - identity: { - type: 'SystemAssigned' - } - properties: { - // organization - friendlyName: aiHubFriendlyName - description: aiHubDescription - - // dependent resources - keyVault: keyVaultId - storageAccount: storageAccountId - } - kind: 'hub' - - resource aiServicesConnection 'connections@2024-07-01-preview' = { - name: '${aiHubName}-connection-AIServices' - properties: { - category: 'AIServices' - target: aiServicesTarget - authType: 'AAD' - isSharedToAll: true - metadata: { - ApiType: 'Azure' - ResourceId: aiServicesId - location: aiServices.location - } - } - } - resource hub_connection_azureai_search 'connections@2024-07-01-preview' = { - name: acsConnectionName - properties: { - category: 'CognitiveSearch' - target: 'https://${aiSearchName}.search.windows.net' - authType: 'AAD' - //useWorkspaceManagedIdentity: false - isSharedToAll: true - metadata: { - ApiType: 'Azure' - ResourceId: aiSearchId - location: searchService.location - } - } - } - - // Resource definition for the capability host - resource capabilityHost 'capabilityHosts@2025-11-01' = { - name: '${aiHubName}-${capabilityHostName}' - properties: { - capabilityHostKind: 'Agents' - } - } - -} - -output aiHubID string = aiHub.id -output aoaiConnectionName string = aoaiConnection -output acsConnectionName string = acsConnectionName diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep deleted file mode 100644 index a81b95d9..00000000 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep +++ /dev/null @@ -1,78 +0,0 @@ -// Creates an Azure AI resource with proxied endpoints for the Azure AI services provider - -@description('Azure region of the deployment') -param location string - -@description('Tags to add to the resources') -param tags object - -@description('AI Project name') -param aiProjectName string - -@description('AI Project display name') -param aiProjectFriendlyName string = aiProjectName - -@description('AI Project description') -param aiProjectDescription string - -@description('Resource ID of the AI Hub resource') -param aiHubId string - -@description('Name for capabilityHost.') -param capabilityHostName string = 'caphost1' - -@description('Name for ACS connection.') -param acsConnectionName string - -@description('Name for ACS connection.') -param aoaiConnectionName string - -//for constructing endpoint -var subscriptionId = subscription().subscriptionId -var resourceGroupName = resourceGroup().name - -var projectConnectionString = '${location}.api.azureml.ms;${subscriptionId};${resourceGroupName};${aiProjectName}' - - -var storageConnections = ['${aiProjectName}/workspaceblobstore'] -var aiSearchConnection = ['${acsConnectionName}'] -var aiServiceConnections = ['${aoaiConnectionName}'] - - -resource aiProject 'Microsoft.MachineLearningServices/workspaces@2023-08-01-preview' = { - name: aiProjectName - location: location - tags: union(tags, { - ProjectConnectionString: projectConnectionString - }) - identity: { - type: 'SystemAssigned' - } - properties: { - // organization - friendlyName: aiProjectFriendlyName - description: aiProjectDescription - - // dependent resources - hubResourceId: aiHubId - - } - kind: 'project' - - // Resource definition for the capability host - resource capabilityHost 'capabilityHosts@2025-11-01' = { - name: '${aiProjectName}-${capabilityHostName}' - properties: { - capabilityHostKind: 'Agents' - aiServicesConnections: aiServiceConnections - vectorStoreConnections: aiSearchConnection - storageConnections: storageConnections - } - } -} - -output aiProjectName string = aiProject.name -output aiProjectResourceId string = aiProject.id -output aiProjectPrincipalId string = aiProject.identity.principalId -output aiProjectWorkspaceId string = aiProject.properties.workspaceId -output projectConnectionString string = aiProject.tags.ProjectConnectionString diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep deleted file mode 100644 index d89f7a03..00000000 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep +++ /dev/null @@ -1,192 +0,0 @@ -// Creates Azure dependent resources for Azure AI studio - -@description('Azure region of the deployment') -param location string = resourceGroup().location - -@description('Tags to add to the resources') -param tags object = {} - -@description('AI services name') -param aiServicesName string - -@description('The name of the Key Vault') -param keyvaultName string - -@description('The name of the AI Search resource') -param aiSearchName string - -@description('Name of the storage account') -param storageName string - -@description('Model name for deployment') -param modelName string - -@description('Model format for deployment') -param modelFormat string - -@description('Model version for deployment') -param modelVersion string - -@description('Model deployment SKU name') -param modelSkuName string - -@description('Model deployment capacity') -param modelCapacity int - -@description('Model/AI Resource deployment location') -param modelLocation string - -@description('The AI Service Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') -param aiServiceAccountResourceId string - -@description('The AI Search Service full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') -param aiSearchServiceResourceId string - -@description('The AI Storage Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') -param aiStorageAccountResourceId string - -var aiServiceExists = aiServiceAccountResourceId != '' -var acsExists = aiSearchServiceResourceId != '' -var aiStorageExists = aiStorageAccountResourceId != '' - -resource keyVault 'Microsoft.KeyVault/vaults@2024-12-01-preview' = { - name: keyvaultName - location: location - tags: tags - properties: { - createMode: 'default' - enabledForDeployment: false - enabledForDiskEncryption: false - enabledForTemplateDeployment: false - enableSoftDelete: true - enableRbacAuthorization: true - networkAcls: { - bypass: 'AzureServices' - defaultAction: 'Deny' - } - sku: { - family: 'A' - name: 'standard' - } - softDeleteRetentionInDays: 7 - tenantId: subscription().tenantId - } -} - - -var aiServiceParts = split(aiServiceAccountResourceId, '/') - -resource existingAIServiceAccount 'Microsoft.CognitiveServices/accounts@2023-05-01' existing = if (aiServiceExists) { - name: aiServiceParts[8] - scope: resourceGroup(aiServiceParts[2], aiServiceParts[4]) -} - -resource aiServices 'Microsoft.CognitiveServices/accounts@2024-06-01-preview' = if(!aiServiceExists) { - name: aiServicesName - location: modelLocation - sku: { - name: 'S0' - } - kind: 'AIServices' // or 'OpenAI' - identity: { - type: 'SystemAssigned' - } - properties: { - customSubDomainName: toLower('${(aiServicesName)}') - publicNetworkAccess: 'Enabled' - } -} -resource modelDeployment 'Microsoft.CognitiveServices/accounts/deployments@2024-06-01-preview'= if(!aiServiceExists){ - parent: aiServices - name: modelName - sku : { - capacity: modelCapacity - name: modelSkuName - } - properties: { - model:{ - name: modelName - format: modelFormat - version: modelVersion - } - } -} - -var acsParts = split(aiSearchServiceResourceId, '/') - -resource existingSearchService 'Microsoft.Search/searchServices@2023-11-01' existing = if (acsExists) { - name: acsParts[8] - scope: resourceGroup(acsParts[2], acsParts[4]) -} -resource aiSearch 'Microsoft.Search/searchServices@2024-06-01-preview' = if(!acsExists) { - name: aiSearchName - location: location - tags: tags - identity: { - type: 'SystemAssigned' - } - properties: { - disableLocalAuth: false - authOptions: { aadOrApiKey: { aadAuthFailureMode: 'http401WithBearerChallenge'}} - encryptionWithCmk: { - enforcement: 'Unspecified' - } - hostingMode: 'default' - partitionCount: 1 - publicNetworkAccess: 'enabled' - replicaCount: 1 - semanticSearch: 'disabled' - } - sku: { - name: 'standard' - } -} - -var aiStorageParts = split(aiStorageAccountResourceId, '/') - -resource existingAIStorageAccount 'Microsoft.Storage/storageAccounts@2023-05-01' existing = if (aiStorageExists) { - name: aiStorageParts[8] - scope: resourceGroup(aiStorageParts[2], aiStorageParts[4]) -} - -param sku string = 'Standard_LRS' - -resource storage 'Microsoft.Storage/storageAccounts@2022-05-01' = if(!aiStorageExists) { - name: storageName - location: location - kind: 'StorageV2' - sku: { - name: sku - } - properties: { - minimumTlsVersion: 'TLS1_2' - allowBlobPublicAccess: false - publicNetworkAccess: 'Enabled' - networkAcls: { - bypass: 'AzureServices' - defaultAction: 'Allow' - virtualNetworkRules: [] - } - allowSharedKeyAccess: false - } -} - -output aiServicesName string = aiServiceExists ? existingAIServiceAccount.name : aiServicesName -output aiservicesID string = aiServiceExists ? existingAIServiceAccount.id : aiServices.id -output aiservicesTarget string = aiServiceExists ? existingAIServiceAccount.properties.endpoint : aiServices.properties.endpoint -output aiServiceAccountResourceGroupName string = aiServiceExists ? aiServiceParts[4] : resourceGroup().name -output aiServiceAccountSubscriptionId string = aiServiceExists ? aiServiceParts[2] : subscription().subscriptionId - -output aiSearchName string = acsExists ? existingSearchService.name : aiSearch.name -output aisearchID string = acsExists ? existingSearchService.id : aiSearch.id -output aiSearchServiceResourceGroupName string = acsExists ? acsParts[4] : resourceGroup().name -output aiSearchServiceSubscriptionId string = acsExists ? acsParts[2] : subscription().subscriptionId - -output storageAccountName string = aiStorageExists ? existingAIStorageAccount.name : storage.name -output storageId string = aiStorageExists ? existingAIStorageAccount.id : storage.id -output storageAccountResourceGroupName string = aiStorageExists ? aiStorageParts[4] : resourceGroup().name -output storageAccountSubscriptionId string = aiStorageExists ? aiStorageParts[2] : subscription().subscriptionId - -output keyvaultId string = keyVault.id -output keyvaultUri string = keyVault.properties.vaultUri - diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep index 09620fe7..28ec235b 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep @@ -25,6 +25,8 @@ module api '../core/host/functions-app.bicep' = { { AzureWebJobsStorage__clientId : identityClientId APPLICATIONINSIGHTS_AUTHENTICATION_STRING: applicationInsightsIdentity + AzureMonitorExporter__credential: 'managedidentity' + AzureMonitorExporter__clientId: identityClientId }) applicationInsightsName: applicationInsightsName appServicePlanId: appServicePlanId diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep index 1a24c115..2902467a 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep @@ -52,8 +52,8 @@ resource virtualNetwork 'Microsoft.Network/virtualNetworks@2023-05-01' = { name: 'delegation' id: resourceId('Microsoft.Network/virtualNetworks/subnets/delegations', vNetName, 'app', 'delegation') properties: { - //Microsoft.App/environments is the correct delegation for Flex Consumption VNet integration - serviceName: 'Microsoft.App/environments' + // The API runs on a dedicated (B1) App Service plan, which requires the Microsoft.Web/serverFarms delegation + serviceName: 'Microsoft.Web/serverFarms' } type: 'Microsoft.Network/virtualNetworks/subnets/delegations' } diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep index 3e8a28f2..9eb0c69c 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep @@ -20,7 +20,7 @@ param kind string = 'functionapp,linux' param appSettings object = {} param allowedOrigins array = [] -var linuxFxVersion string = 'DOTNET-ISOLATED|8.0' +var linuxFxVersion string = 'DOTNET-ISOLATED|10.0' resource storageAccount 'Microsoft.Storage/storageAccounts@2024-01-01' existing = { name: storageAccountName @@ -42,7 +42,7 @@ module functions 'br/public:avm/res/web/site:0.16.0' = { userAssignedResourceIds: [identityId] } siteConfig: { - netFrameworkVersion: 'v8.0' + netFrameworkVersion: 'v10.0' linuxFxVersion: linuxFxVersion cors: { allowedOrigins: union([ 'https://portal.azure.com', 'https://ms.portal.azure.com' ], allowedOrigins) diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep index 8bceb3e1..1d59c152 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep @@ -5,8 +5,8 @@ targetScope = 'subscription' param environmentName string @minLength(1) -@description('Primary location for all resources') -@allowed(['westus2', 'eastus', 'eastus2']) +@description('Primary location for all resources. Must support both Durable Task Scheduler and the agent model deployment.') +@allowed(['eastus2', 'swedencentral']) @metadata({ azd: { type: 'location' @@ -47,41 +47,30 @@ param disableLocalAuth bool = true @description('Id of the user or app to assign application roles') param principalId string = '' -@description('Name for the AI resource and used to derive name of dependent resources.') -param aiHubName string = 'hub-demo' +@description('Name of the Microsoft Foundry resource (AIServices account). Leave empty to generate a unique name.') +param aiFoundryName string = '' -@description('Friendly name for your Hub resource') -param aiHubFriendlyName string = 'Agents Hub resource' +@description('Name of the Microsoft Foundry project.') +param aiProjectName string = 'travel-planner' -@description('Description of your Azure AI resource displayed in AI studio') -param aiHubDescription string = 'This is an example AI resource for use in Azure AI Studio.' +@description('Display name of the Microsoft Foundry project') +param aiProjectFriendlyName string = 'Travel Planner Agents' -@description('Name for the AI project resources.') -param aiProjectName string = 'project-demo' +@description('Description of the Microsoft Foundry project') +param aiProjectDescription string = 'Foundry project hosting the travel planner agents.' -@description('Friendly name for your Azure AI resource') -param aiProjectFriendlyName string = 'Agents Project resource' - -@description('Description of your Azure AI resource displayed in AI studio') -param aiProjectDescription string = 'This is an example AI Project resource for use in Azure AI Studio.' - -@description('Name of the Azure AI Search account') -param aiSearchName string = 'agentaisearch' - -@description('Name for capabilityHost.') -param capabilityHostName string = 'caphost1' - -@description('Name of the Azure AI Services account') -param aiServicesName string = 'agentaiservices' +@description('Whether the Microsoft Foundry resource accepts traffic from public networks') +@allowed(['Enabled', 'Disabled']) +param aiPublicNetworkAccess string = 'Enabled' @description('Model name for deployment') -param modelName string = 'gpt-4o-mini' +param modelName string = 'gpt-5-mini' @description('Model format for deployment') param modelFormat string = 'OpenAI' @description('Model version for deployment') -param modelVersion string = '2024-07-18' +param modelVersion string = '2025-08-07' @description('Model deployment SKU name') param modelSkuName string = 'GlobalStandard' @@ -89,18 +78,9 @@ param modelSkuName string = 'GlobalStandard' @description('Model deployment capacity') param modelCapacity int = 50 -@description('Model deployment location. If you want to deploy an Azure AI resource/model in different location than the rest of the resources created.') +@description('Location of the Microsoft Foundry resource and model deployment, if it should differ from the rest of the resources.') param modelLocation string = location -@description('The AI Service Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') -param aiServiceAccountResourceId string = '' - -@description('The Ai Search Service full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') -param aiSearchServiceResourceId string = '' - -@description('The Ai Storage Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') -param aiStorageAccountResourceId string = '' - @description('The agent ID of the destination recommender agent') param destinationRecommenderAgentId string = 'agent-destination-recommender-agent' @@ -116,8 +96,7 @@ var resourceToken = toLower(uniqueString(subscription().id, rg.id, environmentNa var tags = { 'azd-env-name': environmentName } var functionAppName = !empty(apiServiceName) ? apiServiceName : '${abbrs.webSitesFunctions}api-${resourceToken}' var deploymentStorageContainerName = 'app-package-${take(functionAppName, 32)}-${take(toLower(uniqueString(functionAppName, resourceToken)), 7)}' -var name = toLower('${aiHubName}') -var projectName = toLower('${aiProjectName}') +var foundryName = !empty(aiFoundryName) ? aiFoundryName : 'aif-${resourceToken}' param dtsSkuName string = 'Consumption' param dtsCapacity int = 1 param dtsName string = '' @@ -128,9 +107,6 @@ var webAppName = !empty(webServiceName) ? webServiceName : '${abbrs.webStaticSit var webUri = 'https://${webAppName}.azurestaticapps.net' param webServiceName string = '' -// Create a short, unique suffix, that will be unique to each resource group -var uniqueSuffix = toLower(uniqueString(subscription().id, rg.id, location)) - // Organize resources in a resource group resource rg 'Microsoft.Resources/resourceGroups@2025-04-01' = { name: !empty(resourceGroupName) ? resourceGroupName : '${abbrs.resourcesResourceGroups}${environmentName}' @@ -218,9 +194,9 @@ module api './app/api.bicep' = { AZURE_CLIENT_ID: apiUserAssignedIdentity.outputs.identityClientId DURABLE_TASK_SCHEDULER_CONNECTION_STRING: 'Endpoint=${dts.outputs.dts_URL};Authentication=ManagedIdentity;ClientID=${apiUserAssignedIdentity.outputs.identityClientId}' TASKHUB_NAME: dts.outputs.TASKHUB_NAME - DESTINATION_RECOMMENDER_CONNECTION: aiProject.outputs.projectConnectionString - ITINERARY_PLANNER_CONNECTION: aiProject.outputs.projectConnectionString - LOCAL_RECOMMENDATIONS_CONNECTION: aiProject.outputs.projectConnectionString + DESTINATION_RECOMMENDER_CONNECTION: aiFoundry.outputs.projectEndpoint + ITINERARY_PLANNER_CONNECTION: aiFoundry.outputs.projectEndpoint + LOCAL_RECOMMENDATIONS_CONNECTION: aiFoundry.outputs.projectEndpoint DESTINATION_RECOMMENDER_AGENT_ID: destinationRecommenderAgentId ITINERARY_PLANNER_AGENT_ID: itineraryPlannerAgentId LOCAL_RECOMMENDATIONS_AGENT_ID: localRecommendationsAgentId @@ -234,104 +210,49 @@ module api './app/api.bicep' = { ] } -// Dependent resources for the Azure Machine Learning workspace -module aiDependencies './agent/standard-dependent-resources.bicep' = { +// Microsoft Foundry resource, project, and model deployment used by the agents +module aiFoundry './agent/ai-foundry.bicep' = { scope: rg - name: 'dependencies-${name}-${resourceToken}' + name: 'aiFoundry-${resourceToken}' params: { - location: location - storageName: 'st${resourceToken}' - keyvaultName: 'kv-${name}${resourceToken}' - aiServicesName: '${aiServicesName}${resourceToken}' - aiSearchName: '${aiSearchName}${resourceToken}' + location: modelLocation tags: tags - - // Model deployment parameters + aiFoundryName: foundryName + aiProjectName: toLower(aiProjectName) + aiProjectFriendlyName: aiProjectFriendlyName + aiProjectDescription: aiProjectDescription modelName: modelName modelFormat: modelFormat modelVersion: modelVersion modelSkuName: modelSkuName - modelCapacity: modelCapacity - modelLocation: modelLocation - - aiServiceAccountResourceId: aiServiceAccountResourceId - aiSearchServiceResourceId: aiSearchServiceResourceId - aiStorageAccountResourceId: aiStorageAccountResourceId - } - - dependsOn: [ - storage - ] -} - -module aiHub './agent/standard-ai-hub.bicep' = { - scope: rg - name: '${name}-${resourceToken}' - params: { - // workspace organization - aiHubName: '${name}${uniqueSuffix}' - aiHubFriendlyName: aiHubFriendlyName - aiHubDescription: aiHubDescription - location: location - tags: tags - capabilityHostName: '${name}${uniqueSuffix}${capabilityHostName}' - - aiSearchName: aiDependencies.outputs.aiSearchName - aiSearchId: aiDependencies.outputs.aisearchID - - aiServicesName: aiDependencies.outputs.aiServicesName - aiServicesId: aiDependencies.outputs.aiservicesID - aiServicesTarget: aiDependencies.outputs.aiservicesTarget - - keyVaultId: aiDependencies.outputs.keyvaultId - storageAccountId: aiDependencies.outputs.storageId + modelCapacity: modelCapacity + publicNetworkAccess: aiPublicNetworkAccess } - dependsOn: [ - storage - aiDependencies - ] } -module aiProject './agent/standard-ai-project.bicep' = { - scope: rg - name: '${projectName}-${resourceToken}-deployment' - params: { - // workspace organization - aiProjectName: '${projectName}${uniqueSuffix}' - aiProjectFriendlyName: aiProjectFriendlyName - aiProjectDescription: aiProjectDescription - location: location - tags: tags - - // dependent resources - capabilityHostName: '${projectName}${uniqueSuffix}${capabilityHostName}' +var azureAiUserRoleId = '53ca6127-db72-4b80-b1b0-d745d6d5456d' // Foundry User (formerly Azure AI User) - aiHubId: aiHub.outputs.aiHubID - acsConnectionName: aiHub.outputs.acsConnectionName - aoaiConnectionName: aiHub.outputs.aoaiConnectionName - } - dependsOn:[ - storage - ] -} - -module aiServiceRoleAssignments './agent/ai-service-role-assignments.bicep' = { +// Allow the function app identity to call the Foundry Agent Service +module aiFoundryRoleAssignmentApi './agent/ai-foundry-access.bicep' = { scope: rg - name: 'aiserviceroleassignments${projectName}-${resourceToken}' + name: 'aiFoundryRoleAssignmentApi-${resourceToken}' params: { - aiServicesName: aiDependencies.outputs.aiServicesName - aiProjectPrincipalId: aiProject.outputs.aiProjectPrincipalId - aiProjectId: aiProject.outputs.aiProjectResourceId + aiFoundryName: aiFoundry.outputs.aiFoundryName + roleDefinitionID: azureAiUserRoleId + principalID: apiUserAssignedIdentity.outputs.identityPrincipalId + principalType: 'ServicePrincipal' } } -module aiSearchRoleAssignments './agent/ai-search-role-assignments.bicep' = { +// Allow the deploying user to create and test agents in the Foundry project +module aiFoundryRoleAssignmentUser './agent/ai-foundry-access.bicep' = if (!empty(principalId)) { scope: rg - name: 'aisearchroleassignments${projectName}-${resourceToken}' + name: 'aiFoundryRoleAssignmentUser-${resourceToken}' params: { - aiSearchName: aiDependencies.outputs.aiSearchName - aiProjectPrincipalId: aiProject.outputs.aiProjectPrincipalId - aiProjectId: aiProject.outputs.aiProjectResourceId + aiFoundryName: aiFoundry.outputs.aiFoundryName + roleDefinitionID: azureAiUserRoleId + principalID: principalId + principalType: 'User' } } @@ -374,18 +295,6 @@ module storageQueueDataContributorRoleAssignmentprocessor 'app/storage-Access.bi } } -// Allow access from AI project to storage account using a managed identity -module storageQueueDataContributorRoleAssignmentAIProject 'app/storage-Access.bicep' = { - scope: rg - name: 'storageQueueDataContributorRoleAssignmentAIProject-${resourceToken}' - params: { - storageAccountName: storage.outputs.name - roleDefinitionID: storageQueueDataContributorRoleDefinitionId - principalID: aiProject.outputs.aiProjectPrincipalId - principalType: 'ServicePrincipal' - } -} - module storageQueueDataContributorRoleAssignmentUserIdentityprocessor 'app/storage-Access.bicep' = { scope: rg name: 'storageQueueDataContributorRole-${resourceToken}' @@ -462,24 +371,10 @@ module appInsightsRoleAssignmentApi './core/monitor/appinsights-access.bicep' = ] } -var azureAiDeveloperRoleId = '64702f94-c441-49e6-a78b-ef80e0188fee' // Azure AI Developer role ID -// Enable access to AI Project from the Azure Function user assigned identity -resource AIProjectRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { - name: guid(azureAiDeveloperRoleId, aiProjectName, resourceId('Microsoft.MachineLearningServices/workspaces', aiProjectName), resourceToken) - properties: { - roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', azureAiDeveloperRoleId) - principalId: apiUserAssignedIdentity.outputs.identityPrincipalId - principalType: 'ServicePrincipal' - } - dependsOn: [ - apiUserAssignedIdentity - ] -} - var durableTaskDataContributorRoleDefinitionId = '0ad04412-c4d5-4796-b79c-f76d14c8d402' // Allow access from durable function to storage account using a user assigned managed identity -module dtsRoleAssignment 'app/dts-access.bicep' = { +module dtsRoleAssignment 'app/dts-Access.bicep' = { name: 'dtsRoleAssignment-${resourceToken}' scope: rg params: { @@ -495,7 +390,7 @@ module dtsRoleAssignment 'app/dts-access.bicep' = { ] } -module dtsDashboardRoleAssignment 'app/dts-access.bicep' = { +module dtsDashboardRoleAssignment 'app/dts-Access.bicep' = { name: 'dtsDashboardRoleAssignment-${resourceToken}' scope: rg params: { @@ -540,11 +435,14 @@ output STATIC_WEB_APP_NAME string = webapp.outputs.name output STATIC_WEB_APP_URI string = webapp.outputs.uri output PRE_STATIC_WEB_APP_URI string = webAppName output RESOURCE_GROUP string = rg.name -output PROJECT_CONNECTION_STRING string = aiProject.outputs.projectConnectionString +output AI_FOUNDRY_NAME string = aiFoundry.outputs.aiFoundryName +output AI_PROJECT_NAME string = aiFoundry.outputs.aiProjectName +output AI_MODEL_DEPLOYMENT_NAME string = aiFoundry.outputs.modelDeploymentName +output PROJECT_ENDPOINT string = aiFoundry.outputs.projectEndpoint output STORAGE_CONNECTION__queueServiceUri string = 'https://${storage.outputs.name}.queue.${environment().suffixes.storage}' // Agent outputs output DESTINATION_RECOMMENDER_AGENT_ID string = destinationRecommenderAgentId output ITINERARY_PLANNER_AGENT_ID string = itineraryPlannerAgentId output LOCAL_RECOMMENDATIONS_AGENT_ID string = localRecommendationsAgentId -output AGENT_CONNECTION_STRING string = aiProject.outputs.projectConnectionString +output AGENT_CONNECTION_STRING string = aiFoundry.outputs.projectEndpoint diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json index 0cf80ea9..88ce90f6 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json @@ -79,6 +79,9 @@ }, "localRecommendationsAgentId": { "value": "${LOCAL_RECOMMENDATIONS_AGENT_ID}" + }, + "aiPublicNetworkAccess": { + "value": "${AI_PUBLIC_NETWORK_ACCESS=Enabled}" } } } \ No newline at end of file diff --git a/samples/durable-functions/dotnet/DistributedTracing/DistributedTracing.csproj b/samples/durable-functions/dotnet/DistributedTracing/DistributedTracing.csproj index 06b56e08..5619a719 100644 --- a/samples/durable-functions/dotnet/DistributedTracing/DistributedTracing.csproj +++ b/samples/durable-functions/dotnet/DistributedTracing/DistributedTracing.csproj @@ -1,15 +1,18 @@ - net8.0 + net10.0 v4 Exe - - - - - - + + + + + + + + + diff --git a/samples/durable-functions/dotnet/DistributedTracing/Functions.cs b/samples/durable-functions/dotnet/DistributedTracing/Functions.cs index 0cc2c51e..e5f22b4b 100644 --- a/samples/durable-functions/dotnet/DistributedTracing/Functions.cs +++ b/samples/durable-functions/dotnet/DistributedTracing/Functions.cs @@ -11,7 +11,7 @@ public static class Functions { [Function("StartOrchestration")] public static async Task HttpStart( - [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, + [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req, [DurableClient] DurableTaskClient client, FunctionContext executionContext) { diff --git a/samples/durable-functions/dotnet/DistributedTracing/Program.cs b/samples/durable-functions/dotnet/DistributedTracing/Program.cs index c2df7fbe..7154b6f7 100644 --- a/samples/durable-functions/dotnet/DistributedTracing/Program.cs +++ b/samples/durable-functions/dotnet/DistributedTracing/Program.cs @@ -1,13 +1,31 @@ -using Microsoft.Azure.Functions.Worker; +using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Azure.Functions.Worker.OpenTelemetry; +using Microsoft.Extensions.Azure; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using OpenTelemetry; +using OpenTelemetry.Trace; var host = new HostBuilder() .ConfigureFunctionsWebApplication() - .ConfigureServices(services => + .ConfigureServices((context, services) => { - services.AddApplicationInsightsTelemetryWorkerService(); - services.ConfigureFunctionsApplicationInsights(); + var connectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]; + if (!string.IsNullOrWhiteSpace(connectionString)) + { + services.AddAzureClientsCore(); + services.AddOptions() + .Configure((options, factory) => + { + options.ConnectionString = connectionString; + options.Credential = factory.CreateTokenCredential( + context.Configuration.GetSection("AzureMonitorExporter")); + }); + services.AddOpenTelemetry() + .UseFunctionsWorkerDefaults() + .WithTracing(tracing => tracing.AddSource("Microsoft.DurableTask")) + .UseAzureMonitorExporter(); + } }) .Build(); diff --git a/samples/durable-functions/dotnet/DistributedTracing/README.md b/samples/durable-functions/dotnet/DistributedTracing/README.md index 0f1e1b13..94e9f961 100644 --- a/samples/durable-functions/dotnet/DistributedTracing/README.md +++ b/samples/durable-functions/dotnet/DistributedTracing/README.md @@ -8,23 +8,26 @@ This sample demonstrates how to enable distributed tracing in Durable Functions ## Prerequisites -1. [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) or later +1. [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) or later 2. [Docker](https://www.docker.com/products/docker-desktop/) 3. [Azure Functions Core Tools](https://learn.microsoft.com/azure/azure-functions/functions-run-local) v4+ ## Quick Run (Local with Jaeger) 1. Start the infrastructure: + ```bash docker compose up -d ``` 2. Run the function app: + ```bash func start ``` 3. Trigger an orchestration: + ```bash curl -X POST http://localhost:7071/api/StartOrchestration ``` @@ -33,8 +36,28 @@ This sample demonstrates how to enable distributed tracing in Durable Functions - **Jaeger UI:** http://localhost:16686 - **DTS Dashboard:** http://localhost:8082 +The compose file starts Jaeger but does not configure the Functions host or worker to export telemetry to it. An OTLP exporter and endpoint configuration are also needed; starting Jaeger alone does not send it traces. + ## Key Configuration +### HTTP authentication + +`StartOrchestration` requires a function or host key in Azure. Core Tools skips key enforcement locally by default; use `func start --enableAuth` to exercise it locally. + +For a deployed app, retrieve a non-admin host key into a shell variable and send it in a header: + +```bash +FUNCTION_KEY=$(az functionapp keys list \ + --resource-group "$AZURE_RESOURCE_GROUP" \ + --name "$AZURE_FUNCTION_NAME" --query functionKeys.default --output tsv) +curl -X POST -H "x-functions-key: ${FUNCTION_KEY}" \ + "https://${AZURE_FUNCTION_NAME}.azurewebsites.net/api/StartOrchestration" +``` + +Do not use the master key or expose keys in source control, logs, or browser code. Keys do not provide per-user or per-instance authorization; managed identity for backend services is unchanged. The returned Durable management URLs contain a system key: keep those URLs secret and poll them as returned. + +### Durable tracing + Distributed tracing is enabled in `host.json`: ```json @@ -54,6 +77,8 @@ Distributed tracing is enabled in `host.json`: When deployed to Azure with Application Insights configured: +The Functions host uses OpenTelemetry and the Durable Task distributed tracing configuration above. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports telemetry to Azure Monitor and captures the `Microsoft.DurableTask` activity source to connect the starter to the orchestration trace. For user-assigned managed identity authentication, set `AzureMonitorExporter__credential` to `managedidentity` and `AzureMonitorExporter__clientId` to the identity's client ID, and grant that identity the Monitoring Metrics Publisher role on Application Insights. + 1. Navigate to your Application Insights resource 2. Go to **Transaction Search** 3. Filter for events with Durable Functions prefixes (`orchestration:`, `activity:`) diff --git a/samples/durable-functions/dotnet/DistributedTracing/host.json b/samples/durable-functions/dotnet/DistributedTracing/host.json index 2174cb2e..cd854593 100644 --- a/samples/durable-functions/dotnet/DistributedTracing/host.json +++ b/samples/durable-functions/dotnet/DistributedTracing/host.json @@ -1,12 +1,7 @@ { "version": "2.0", + "telemetryMode": "OpenTelemetry", "logging": { - "applicationInsights": { - "samplingSettings": { - "isEnabled": true, - "excludedTypes": "Request" - } - }, "logLevel": { "DurableTask.Core": "Warning" } diff --git a/samples/durable-functions/dotnet/LargePayload/LargePayload.csproj b/samples/durable-functions/dotnet/LargePayload/LargePayload.csproj index 8dce54dc..158f441b 100644 --- a/samples/durable-functions/dotnet/LargePayload/LargePayload.csproj +++ b/samples/durable-functions/dotnet/LargePayload/LargePayload.csproj @@ -1,6 +1,6 @@ - net8.0 + net10.0 v4 Exe enable @@ -9,13 +9,15 @@ - + - - - + + + + + diff --git a/samples/durable-functions/dotnet/LargePayload/LargePayloadOrchestration.cs b/samples/durable-functions/dotnet/LargePayload/LargePayloadOrchestration.cs index e2b7dc66..e86bd2e8 100644 --- a/samples/durable-functions/dotnet/LargePayload/LargePayloadOrchestration.cs +++ b/samples/durable-functions/dotnet/LargePayload/LargePayloadOrchestration.cs @@ -15,7 +15,7 @@ public static class LargePayloadOrchestration [Function("StartLargePayload")] public static async Task HttpStart( - [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req, + [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, [DurableClient] DurableTaskClient client, FunctionContext executionContext) { @@ -41,8 +41,10 @@ public static async Task LargePayloadRoundTrip( LargePayloadRequest request = context.GetInput() ?? throw new InvalidOperationException("The orchestration input payload was not provided."); + ValidatePayload(request.Payload, request.RequestedPayloadBytes); string echoedPayload = await context.CallActivityAsync(nameof(EchoLargePayload), request.Payload) ?? throw new InvalidOperationException("The activity did not return a payload."); + ValidatePayload(echoedPayload, request.RequestedPayloadBytes); int orchestrationInputBytes = GetUtf8ByteCount(request.Payload); int activityOutputBytes = GetUtf8ByteCount(echoedPayload); @@ -76,7 +78,7 @@ public static string EchoLargePayload( [Function("Hello")] public static async Task Hello( - [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req) + [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req) { HttpResponseData response = req.CreateResponse(HttpStatusCode.OK); await response.WriteStringAsync("LargePayload sample is running. POST /api/StartLargePayload to start a >1 MB orchestration."); @@ -99,6 +101,25 @@ private static string CreatePayload(int payloadSizeBytes) }); } + private static void ValidatePayload(string payload, int expectedSizeBytes) + { + if (payload.Length != expectedSizeBytes) + { + throw new InvalidOperationException("The payload size did not match the requested size."); + } + + const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + uint state = 0x00C0FFEEu; + for (int i = 0; i < payload.Length; i++) + { + state = (state * 1664525) + 1013904223; + if (payload[i] != Alphabet[(int)(state >> 26)]) + { + throw new InvalidOperationException($"Invalid payload content at offset {i}."); + } + } + } + private static int GetPositiveIntSetting(string key, int defaultValue) { string? rawValue = Environment.GetEnvironmentVariable(key); diff --git a/samples/durable-functions/dotnet/LargePayload/Program.cs b/samples/durable-functions/dotnet/LargePayload/Program.cs index 4b07a32c..064503d1 100644 --- a/samples/durable-functions/dotnet/LargePayload/Program.cs +++ b/samples/durable-functions/dotnet/LargePayload/Program.cs @@ -1,13 +1,28 @@ -using Microsoft.Azure.Functions.Worker; +using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Azure.Functions.Worker.OpenTelemetry; +using Microsoft.Extensions.Azure; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; var host = new HostBuilder() .ConfigureFunctionsWebApplication() - .ConfigureServices(services => + .ConfigureServices((context, services) => { - services.AddApplicationInsightsTelemetryWorkerService(); - services.ConfigureFunctionsApplicationInsights(); + string? connectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]; + if (!string.IsNullOrWhiteSpace(connectionString)) + { + services.AddAzureClientsCore(); + services.AddOptions() + .Configure((options, factory) => + { + options.ConnectionString = connectionString; + options.Credential = factory.CreateTokenCredential( + context.Configuration.GetSection("AzureMonitorExporter")); + }); + services.AddOpenTelemetry() + .UseFunctionsWorkerDefaults() + .UseAzureMonitorExporter(); + } }) .Build(); diff --git a/samples/durable-functions/dotnet/LargePayload/README.md b/samples/durable-functions/dotnet/LargePayload/README.md index 78c52ece..6ce1f9a0 100644 --- a/samples/durable-functions/dotnet/LargePayload/README.md +++ b/samples/durable-functions/dotnet/LargePayload/README.md @@ -27,7 +27,9 @@ The flow is intentionally simple: 1. An HTTP trigger starts an orchestration with a payload larger than 1 MB. 2. The orchestrator sends that payload to a single activity. 3. The activity echoes the payload back. -4. The orchestration returns a small summary proving the payload survived the round-trip. +4. The orchestrator checks both its input and the activity output character by character against the expected deterministic content, without allocating another full payload, then returns a small summary. + +An equal byte count is not enough: same-length corruption, an unresolved blob reference, or a truncated payload fails the orchestration. `PayloadsMatch` also compares the full input and output, not just their lengths. This is exactly why large payload support exists: without blob offload, a payload this size would be too large to flow through DTS messages directly. @@ -42,7 +44,7 @@ The sample enables these settings in `host.json`: "connectionStringName": "DTS_CONNECTION_STRING", "payloadStorageEnabled": true, "payloadStorageThresholdBytes": 262144, - "payloadStorageMaxPayloadBytes": 15728640 + "payloadStorageMaxSizeBytes": 15728640 }, "hubName": "%TASKHUB_NAME%" } @@ -59,31 +61,31 @@ The sample uses a deterministic, low-compressibility **1.5 MiB** payload by defa ### Maximum payload size -`payloadStorageThresholdBytes` controls *when* a payload is externalized. A separate setting, `payloadStorageMaxPayloadBytes`, controls the **largest single serialized UTF-8 payload** the runtime will externalize: +`payloadStorageThresholdBytes` controls *when* a payload is externalized. A separate setting, `payloadStorageMaxSizeBytes`, controls the **largest single serialized UTF-8 payload** the runtime will externalize: -- If you don't set `payloadStorageMaxPayloadBytes`, the default maximum is **10 MB (10,485,760 bytes, shown as 10,240 KB in the error message)**. +- If you don't set `payloadStorageMaxSizeBytes`, the default maximum is **10 MB (10,485,760 bytes, shown as 10,240 KB in the error message)**. - A request whose payload exceeds the maximum **fails fast** — before the orchestration is scheduled — with an error like: ```text Payload size 10742 KB exceeds the configured maximum of 10240 KB. Reduce the payload size or increase the max payload size limit. ``` -- This is a **configurable limit, not a hard product limit**. To allow larger payloads, raise `payloadStorageMaxPayloadBytes` in `host.json`. This sample sets it to `15728640` (15 MiB), including JSON serialization overhead. +- This is a **configurable limit, not a hard product limit**. To allow larger payloads, raise `payloadStorageMaxSizeBytes` in `host.json`. This sample sets it to `15728640` (15 MiB), including JSON serialization overhead. -#### `PAYLOAD_SIZE_BYTES` is not `payloadStorageMaxPayloadBytes` +#### `PAYLOAD_SIZE_BYTES` is not `payloadStorageMaxSizeBytes` These two settings are easy to confuse but do completely different things: | Setting | Where it lives | What it controls | |---|---|---| | `PAYLOAD_SIZE_BYTES` | app setting / `local.settings.json` | How many bytes of test data **this sample generates** for its demo payload. | -| `payloadStorageMaxPayloadBytes` | `host.json` | The **maximum** size the runtime will externalize. Payloads larger than this fail fast. | +| `payloadStorageMaxSizeBytes` | `host.json` | The **maximum** size the runtime will externalize. Payloads larger than this fail fast. | -If you raise `PAYLOAD_SIZE_BYTES` above `payloadStorageMaxPayloadBytes` (for example `PAYLOAD_SIZE_BYTES=11000000` against the default 10 MB cap), the run fails **by design** with the error above. Set the cap above the generated data size, leaving room for the JSON string quotes and request fields. Setting the two values equal can still exceed the cap after serialization. +If you raise `PAYLOAD_SIZE_BYTES` above `payloadStorageMaxSizeBytes` (for example `PAYLOAD_SIZE_BYTES=11000000` against the default 10 MB cap), the run fails **by design** with the error above. Set the cap above the generated data size, leaving room for the JSON string quotes and request fields. Setting the two values equal can still exceed the cap after serialization. ## Prerequisites -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) +- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) - [Azure Functions Core Tools v4](https://learn.microsoft.com/azure/azure-functions/functions-run-local) - [Docker](https://www.docker.com/products/docker-desktop/) - [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) @@ -150,6 +152,12 @@ If you raise `PAYLOAD_SIZE_BYTES` above `payloadStorageMaxPayloadBytes` (for exa The extension stores payload blobs with gzip content encoding, so Azure shows the compressed on-disk size. Because this sample uses low-compressibility payload content, the stored blob sizes should stay reasonably close to the logical 1.5 MiB payload instead of collapsing to a tiny repetitive-text blob. +### Blob retention policy + +This sample configures no time-based Blob Storage lifecycle rule or scheduled cleanup. Do not treat orchestration completion as a guarantee that payload blobs have been deleted. Keep `durabletask-payloads` available while any referencing instance can run, retry, replay, or be inspected with inputs/outputs. + +For a retained environment, define an operational retention period covering the longest orchestration lifetime, recovery window, and history-access requirements. After all referencing instances are terminal and that period has elapsed, purge their durable histories and verify payload cleanup for the deployed extension version; remove remaining unreferenced blobs with an instance-aware cleanup process. Do not apply a blanket age-based deletion rule to live payloads: deleting a still-referenced blob breaks replay and status retrieval. Soft-deleted blobs and versions may remain billable under the storage account's retention settings. For this disposable sample, deleting the dedicated environment under **Clean up** also removes its storage. + ## Local settings | Setting | Description | Default | @@ -157,7 +165,7 @@ The extension stores payload blobs with gzip content encoding, so Azure shows th | `DTS_CONNECTION_STRING` | DTS emulator or Azure connection string | `Endpoint=http://localhost:8080;Authentication=None` | | `TASKHUB_NAME` | Task hub name | `default` | | `AzureWebJobsStorage` | Storage for Functions host state and payload blobs | `UseDevelopmentStorage=true` locally | -| `PAYLOAD_SIZE_BYTES` | Size of the test payload this sample generates. Keep it below `payloadStorageMaxPayloadBytes` (15 MiB in this sample), leaving room for JSON serialization overhead. | `1572864` | +| `PAYLOAD_SIZE_BYTES` | Size of the test payload this sample generates. Keep it below `payloadStorageMaxSizeBytes` (15 MiB in this sample), leaving room for JSON serialization overhead. | `1572864` | ## Deploy to Azure with AZD @@ -179,9 +187,10 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p The deployment provisions: - an Azure Function App - - a storage account used for `AzureWebJobsStorage` + - a storage account used for `AzureWebJobsStorage`, with a blob private endpoint - a Durable Task Scheduler resource and task hub - - a user-assigned managed identity with the required DTS and storage permissions + - Application Insights and Log Analytics + - a user-assigned managed identity with the required DTS, storage, and monitoring permissions 3. Load the environment values: @@ -192,10 +201,14 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p 4. Start the orchestration in Azure: ```bash - curl -X POST "https://${AZURE_FUNCTION_NAME}.azurewebsites.net/api/StartLargePayload" + FUNCTION_KEY=$(az functionapp keys list \ + --resource-group "$AZURE_RESOURCE_GROUP" \ + --name "$AZURE_FUNCTION_NAME" --query functionKeys.default --output tsv) + curl -X POST -H "x-functions-key: ${FUNCTION_KEY}" \ + "https://${AZURE_FUNCTION_NAME}.azurewebsites.net/api/StartLargePayload" ``` -5. Verify payload blobs in Azure storage: +5. Verify payload blobs in Azure storage. The storage firewall denies public access by default; the deployment script allows the deploying machine's IP so this command can run from there: ```bash az storage blob list \ @@ -207,6 +220,20 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p 6. Open the DTS dashboard URL in the Azure portal to inspect the orchestration history. +## HTTP authentication + +All HTTP triggers, including `Hello`, require a function or host key in Azure. The example uses a non-admin host key; never use the master key for application requests. Keep keys out of source control, logs, shared command output, and browser bundles; rotate them if exposed. Keys grant access, not per-user or per-instance authorization. Managed identity for DTS and Storage is unchanged. + +Core Tools normally skips HTTP key enforcement locally, so the local examples need no key. Use `func start --enableAuth` to exercise key enforcement. The returned Durable management URLs carry a system key in their query string: treat the entire URLs as secrets and poll them as returned, without replacing their key with the starter key. + +## Telemetry + +The Functions host uses OpenTelemetry (`telemetryMode` in `host.json`). + +When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker registers OpenTelemetry and exports to Azure Monitor. The exporter authenticates with the app's managed identity through the dedicated `AzureMonitorExporter` settings (`AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`), so Application Insights local authentication can stay disabled. Without that connection string, as in local emulator runs, the worker does not export. + +In Application Insights, inspect `requests`, `dependencies`, and `traces` for exported telemetry. Payload contents are not logged. + ## Files to look at - `LargePayloadOrchestration.cs` — HTTP starter, orchestrator, and echo activity diff --git a/samples/durable-functions/dotnet/LargePayload/host.json b/samples/durable-functions/dotnet/LargePayload/host.json index 480e57f6..b66ffd37 100644 --- a/samples/durable-functions/dotnet/LargePayload/host.json +++ b/samples/durable-functions/dotnet/LargePayload/host.json @@ -1,18 +1,10 @@ { "version": "2.0", + "telemetryMode": "OpenTelemetry", "logging": { - "applicationInsights": { - "samplingSettings": { - "isEnabled": true, - "excludedTypes": "Request" - }, - "enableLiveMetricsFilters": true, - "logLevel": { - "Host.Triggers.DurableTask": "Information" - } - }, "logLevel": { - "Function": "Information" + "Function": "Information", + "Host.Triggers.DurableTask": "Information" } }, "extensions": { @@ -22,7 +14,7 @@ "connectionStringName": "DTS_CONNECTION_STRING", "payloadStorageEnabled": true, "payloadStorageThresholdBytes": 262144, - "payloadStorageMaxPayloadBytes": 15728640 + "payloadStorageMaxSizeBytes": 15728640 }, "hubName": "%TASKHUB_NAME%" } diff --git a/samples/durable-functions/dotnet/LargePayload/infra/app/durable-function.bicep b/samples/durable-functions/dotnet/LargePayload/infra/app/durable-function.bicep index 0611a63b..751ff10d 100644 --- a/samples/durable-functions/dotnet/LargePayload/infra/app/durable-function.bicep +++ b/samples/durable-functions/dotnet/LargePayload/infra/app/durable-function.bicep @@ -31,9 +31,10 @@ module durableFunction '../core/host/functions.bicep' = { AzureWebJobsStorage__clientId : identityClientId AzureWebJobsStorage__credential : 'managedidentity' APPLICATIONINSIGHTS_AUTHENTICATION_STRING: applicationInsightsIdentity + AzureMonitorExporter__credential: 'managedidentity' + AzureMonitorExporter__clientId: identityClientId DTS_CONNECTION_STRING: 'Endpoint=${dtsURL};Authentication=ManagedIdentity;ClientID=${identityClientId}' TASKHUB_NAME: taskHubName - AZURE_CLIENT_ID: identityClientId }) applicationInsightsName: applicationInsightsName appServicePlanId: appServicePlanId diff --git a/samples/durable-functions/dotnet/LargePayload/infra/main.bicep b/samples/durable-functions/dotnet/LargePayload/infra/main.bicep index 26cad820..27dddc9e 100644 --- a/samples/durable-functions/dotnet/LargePayload/infra/main.bicep +++ b/samples/durable-functions/dotnet/LargePayload/infra/main.bicep @@ -118,7 +118,7 @@ module durableFunction './app/durable-function.bicep' = { applicationInsightsName: monitoring.outputs.applicationInsightsName appServicePlanId: appServicePlan.outputs.id runtimeName: 'dotnet-isolated' - runtimeVersion: '8.0' + runtimeVersion: '10.0' storageAccountName: storage.outputs.name deploymentStorageContainerName: deploymentStorageContainerName identityId: durableFunctionUserAssignedIdentity.outputs.identityId diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadOrchestration.cs b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadOrchestration.cs index 36c3e447..e61ad135 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadOrchestration.cs +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/LargePayloadOrchestration.cs @@ -16,7 +16,7 @@ public static class LargePayloadOrchestration [Function("StartLargePayload")] public static async Task HttpStart( - [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req, + [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, [DurableClient] DurableTaskClient client, FunctionContext executionContext) { @@ -43,29 +43,39 @@ public static async Task LargePayloadFanOutFanIn( LargePayloadFanOutRequest request = context.GetInput() ?? throw new InvalidOperationException("The orchestration input payload was not provided."); - List> tasks = new(request.ActivityCount); + List> tasks = new(request.ActivityCount); for (int i = 0; i < request.ActivityCount; i++) { - tasks.Add(context.CallActivityAsync( - nameof(GenerateLargePayload), + tasks.Add(context.CallSubOrchestratorAsync( + nameof(GenerateAndValidatePayload), new LargePayloadActivityRequest(i + 1, request.RequestedPayloadBytes))); } - string[] payloads = await Task.WhenAll(tasks); - if (payloads.Any(payload => payload.StartsWith("blob:v1:", StringComparison.Ordinal))) - { - throw new InvalidOperationException("The orchestrator received a payload token instead of the resolved payload."); - } - - int[] individualPayloadBytes = payloads.Select(GetUtf8ByteCount).ToArray(); + LargePayloadActivitySummary[] summaries = await Task.WhenAll(tasks); + int[] individualPayloadBytes = summaries.Select(summary => summary.PayloadBytes).ToArray(); return new LargePayloadFanOutSummary( - ActivityCount: payloads.Length, + ActivityCount: summaries.Length, RequestedPayloadBytesPerActivity: request.RequestedPayloadBytes, IndividualPayloadBytes: individualPayloadBytes, - TotalPayloadBytes: individualPayloadBytes.Sum(), + TotalPayloadBytes: individualPayloadBytes.Sum(bytes => (long)bytes), AllPayloadsExceededOneMiB: individualPayloadBytes.All(bytes => bytes > OneMiB), - AllPayloadsMatchRequestedSize: individualPayloadBytes.All(bytes => bytes == request.RequestedPayloadBytes)); + AllPayloadsMatchRequestedSize: individualPayloadBytes.All(bytes => bytes == request.RequestedPayloadBytes), + AllPayloadsMatchExpectedContent: summaries.All(summary => summary.ContentMatches)); + } + + [Function(nameof(GenerateAndValidatePayload))] + public static async Task GenerateAndValidatePayload( + [OrchestrationTrigger] TaskOrchestrationContext context) + { + LargePayloadActivityRequest request = context.GetInput() + ?? throw new InvalidOperationException("The activity request was not provided."); + + // Keep large results in separate histories; the parent only receives small summaries. + string payload = await context.CallActivityAsync(nameof(GenerateLargePayload), request) + ?? throw new InvalidOperationException("The activity did not return a payload."); + ValidatePayload(payload, request.ActivityNumber, request.RequestedPayloadBytes); + return new LargePayloadActivitySummary(GetUtf8ByteCount(payload), ContentMatches: true); } [Function(nameof(GenerateLargePayload))] @@ -87,7 +97,7 @@ public static string GenerateLargePayload( [Function("Hello")] public static async Task Hello( - [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req) + [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req) { HttpResponseData response = req.CreateResponse(HttpStatusCode.OK); await response.WriteStringAsync("LargePayloadFanOutFanIn sample is running. POST /api/StartLargePayload to start parallel >1 MB activities."); @@ -110,6 +120,25 @@ private static string CreatePayload(int activityNumber, int payloadSizeBytes) }); } + private static void ValidatePayload(string payload, int activityNumber, int expectedSizeBytes) + { + if (payload.Length != expectedSizeBytes) + { + throw new InvalidOperationException($"Activity {activityNumber} returned an unexpected payload size."); + } + + const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + uint state = 0x00C0FFEEu + (uint)activityNumber; + for (int i = 0; i < payload.Length; i++) + { + state = (state * 1664525) + 1013904223; + if (payload[i] != Alphabet[(int)(state >> 26)]) + { + throw new InvalidOperationException($"Activity {activityNumber} returned invalid payload content at offset {i}."); + } + } + } + private static int GetPositiveIntSetting(string key, int defaultValue) { string? rawValue = Environment.GetEnvironmentVariable(key); @@ -133,10 +162,13 @@ public sealed record LargePayloadFanOutRequest(int ActivityCount, int RequestedP public sealed record LargePayloadActivityRequest(int ActivityNumber, int RequestedPayloadBytes); +public sealed record LargePayloadActivitySummary(int PayloadBytes, bool ContentMatches); + public sealed record LargePayloadFanOutSummary( int ActivityCount, int RequestedPayloadBytesPerActivity, int[] IndividualPayloadBytes, - int TotalPayloadBytes, + long TotalPayloadBytes, bool AllPayloadsExceededOneMiB, - bool AllPayloadsMatchRequestedSize); + bool AllPayloadsMatchRequestedSize, + bool AllPayloadsMatchExpectedContent); diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md index 83d72c91..cf7e4790 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md @@ -25,9 +25,16 @@ If you want the smallest possible example, start with the sibling [LargePayload] The flow is intentionally parallel: 1. An HTTP trigger starts an orchestration with a small request specifying the activity count and payload size. -2. The orchestrator fans out to multiple activities. -3. Each activity generates a payload larger than 1 MB and returns it to the orchestrator. -4. The orchestrator fans in and returns a small summary proving every activity payload survived the round-trip. +2. The orchestrator fans out to child orchestrations, each of which calls one activity. +3. Each activity generates a payload larger than 1 MB and returns it to its child orchestrator. +4. Each child validates every character against the deterministic sequence for its activity number, without allocating a second expected payload, and returns only a small summary. +5. The parent fans in the summaries, never collecting the large activity results in its own history or a `string[]`. + +This reduces the parent's retained data to O(activity count) small summaries rather than O(activity count x payload size). It is not streaming blob deserialization: each child still materializes one payload, and concurrent children can consume memory on the same worker. Size worker concurrency and activity counts accordingly. + +The tradeoff is one extra child orchestration and its scheduling/history overhead per activity. `TotalPayloadBytes` is a 64-bit total so aggregating more than 2 GiB does not overflow. + +The orchestration history shape has changed from direct activity calls to child orchestrations. Before deploying over an older version, drain existing instances or deploy with a new task hub; do not replay in-flight instances against the changed orchestration. This is exactly why large payload support exists: without blob offload, payloads this size would be too large to flow through DTS messages directly. @@ -76,7 +83,7 @@ The sample uses **three deterministic, low-compressibility 1.5 MiB activity payl These two settings are easy to confuse but do completely different things: | Setting | Where it lives | What it controls | -|---|---|---| +| --- | --- | --- | | `PAYLOAD_SIZE_BYTES` | app setting / `local.settings.json` | How many bytes of test data **each activity generates** for its demo payload. | | `payloadStorageMaxSizeBytes` | `host.json` | The **maximum** size of any single payload the runtime will externalize. Larger payloads fail fast. | @@ -137,7 +144,8 @@ If you raise `PAYLOAD_SIZE_BYTES` above `payloadStorageMaxSizeBytes` (for exampl "IndividualPayloadBytes": [1572864, 1572864, 1572864], "TotalPayloadBytes": 4718592, "AllPayloadsExceededOneMiB": true, - "AllPayloadsMatchRequestedSize": true + "AllPayloadsMatchRequestedSize": true, + "AllPayloadsMatchExpectedContent": true } } ``` @@ -153,10 +161,18 @@ If you raise `PAYLOAD_SIZE_BYTES` above `payloadStorageMaxSizeBytes` (for exampl The extension stores payload blobs with gzip content encoding, so Azure shows the compressed on-disk size. Because this sample uses low-compressibility payload content, the stored blob sizes should stay reasonably close to the logical 1.5 MiB activity payloads instead of collapsing to tiny repetitive-text blobs. +Length alone is not the integrity check: a same-length substitution, reordered payload from another activity, truncation, or unresolved blob token fails validation and fails the orchestration rather than returning a successful summary. + +### Blob retention policy + +This sample configures no time-based Blob Storage lifecycle rule or scheduled cleanup. Do not treat orchestration completion as a guarantee that payload blobs have been deleted. Keep `durabletask-payloads` available while any referencing parent or child instance can run, retry, replay, or be inspected with inputs/outputs. + +For a retained environment, define an operational retention period covering the longest orchestration lifetime, recovery window, and history-access requirements. After all referencing instances are terminal and that period has elapsed, purge their durable histories and verify payload cleanup for the deployed extension version; remove remaining unreferenced blobs with an instance-aware cleanup process. Do not apply a blanket age-based deletion rule to live payloads: deleting a still-referenced blob breaks replay and status retrieval. Soft-deleted blobs and versions may remain billable under the storage account's retention settings. For this disposable sample, deleting the dedicated environment under **Clean up** also removes its storage. + ## Local settings | Setting | Description | Default | -|---|---|---| +| --- | --- | --- | | `DTS_CONNECTION_STRING` | DTS emulator or Azure connection string | `Endpoint=http://localhost:8080;Authentication=None` | | `TASKHUB_NAME` | Task hub name | `default` | | `AzureWebJobsStorage` | Storage for Functions host state and payload blobs | `UseDevelopmentStorage=true` locally | @@ -197,7 +213,11 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p 4. Start the orchestration in Azure: ```bash - curl -X POST "https://${AZURE_FUNCTION_NAME}.azurewebsites.net/api/StartLargePayload" + FUNCTION_KEY=$(az functionapp keys list \ + --resource-group "$AZURE_RESOURCE_GROUP" \ + --name "$AZURE_FUNCTION_NAME" --query functionKeys.default --output tsv) + curl -X POST -H "x-functions-key: ${FUNCTION_KEY}" \ + "https://${AZURE_FUNCTION_NAME}.azurewebsites.net/api/StartLargePayload" ``` 5. Verify payload blobs in Azure storage. The storage firewall denies public access by default; the deployment script allows the deploying machine's IP so this command can run from there: @@ -212,6 +232,12 @@ This sample includes `azure.yaml`, `infra/`, and deployment scripts so you can p 6. Open the DTS dashboard URL in the Azure portal to inspect the orchestration history. +## HTTP authentication + +All HTTP triggers, including `Hello`, require a function or host key in Azure. The example uses a non-admin host key; never use the master key for application requests. Keep keys out of source control, logs, shared command output, and browser bundles; rotate them if exposed. Keys grant access, not per-user or per-instance authorization. Managed identity for DTS and Storage is unchanged. + +Core Tools normally skips HTTP key enforcement locally, so the local examples need no key. Use `func start --enableAuth` to exercise key enforcement. The returned Durable management URLs carry a system key in their query string: treat the entire URLs as secrets and poll them as returned, without replacing their key with the starter key. + ## Telemetry The Functions host uses OpenTelemetry (`telemetryMode` in `host.json`). diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/core/host/functions-flexconsumption.bicep b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/core/host/functions-flexconsumption.bicep index d6a5e632..650fc2c5 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/core/host/functions-flexconsumption.bicep +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/infra/core/host/functions-flexconsumption.bicep @@ -14,10 +14,10 @@ param identityId string // Runtime Properties @allowed([ - 'dotnet-isolated', 'node', 'python', 'java', 'powershell', 'custom' + 'dotnet-isolated' ]) param runtimeName string -@allowed(['3.10', '3.11', '7.4', '8.0', '10', '11', '17', '20']) +@allowed(['10.0', '11.0']) param runtimeVersion string param kind string = 'functionapp,linux' diff --git a/samples/durable-functions/dotnet/Saga/DurableFunctionsSaga.csproj b/samples/durable-functions/dotnet/Saga/DurableFunctionsSaga.csproj index 2df2669c..86e6916f 100644 --- a/samples/durable-functions/dotnet/Saga/DurableFunctionsSaga.csproj +++ b/samples/durable-functions/dotnet/Saga/DurableFunctionsSaga.csproj @@ -1,6 +1,6 @@ - net8.0 + net10.0 v4 Exe enable @@ -9,16 +9,20 @@ - + - + - - + + - - + + + + + + diff --git a/samples/durable-functions/dotnet/Saga/Functions/HttpTriggers.cs b/samples/durable-functions/dotnet/Saga/Functions/HttpTriggers.cs index 8511f6e6..c363542a 100644 --- a/samples/durable-functions/dotnet/Saga/Functions/HttpTriggers.cs +++ b/samples/durable-functions/dotnet/Saga/Functions/HttpTriggers.cs @@ -21,7 +21,7 @@ public HttpTriggers(ILogger logger) [Function("StartOrderProcessing")] public async Task StartOrderProcessing( - [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "orders")] HttpRequestData req, + [HttpTrigger(AuthorizationLevel.Function, "post", Route = "orders")] HttpRequestData req, [DurableClient] DurableTaskClient client) { _logger.LogInformation("Processing order request"); @@ -72,7 +72,7 @@ await response.WriteAsJsonAsync(new [Function("GetOrderStatus")] public async Task GetOrderStatus( - [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "orders/{instanceId}")] HttpRequestData req, + [HttpTrigger(AuthorizationLevel.Function, "get", Route = "orders/{instanceId}")] HttpRequestData req, string instanceId, [DurableClient] DurableTaskClient client) { @@ -99,7 +99,7 @@ await response.WriteAsJsonAsync(new [Function("TerminateOrder")] public async Task TerminateOrder( - [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "orders/{instanceId}/terminate")] HttpRequestData req, + [HttpTrigger(AuthorizationLevel.Function, "post", Route = "orders/{instanceId}/terminate")] HttpRequestData req, string instanceId, [DurableClient] DurableTaskClient client) { diff --git a/samples/durable-functions/dotnet/Saga/Program.cs b/samples/durable-functions/dotnet/Saga/Program.cs index cc057033..0336e301 100644 --- a/samples/durable-functions/dotnet/Saga/Program.cs +++ b/samples/durable-functions/dotnet/Saga/Program.cs @@ -1,8 +1,29 @@ +using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Azure.Functions.Worker.OpenTelemetry; +using Microsoft.Extensions.Azure; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() + .ConfigureServices((context, services) => + { + string? connectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]; + if (!string.IsNullOrWhiteSpace(connectionString)) + { + services.AddAzureClientsCore(); + services.AddOptions() + .Configure((options, factory) => + { + options.ConnectionString = connectionString; + options.Credential = factory.CreateTokenCredential( + context.Configuration.GetSection("AzureMonitorExporter")); + }); + services.AddOpenTelemetry() + .UseFunctionsWorkerDefaults() + .UseAzureMonitorExporter(); + } + }) .Build(); host.Run(); diff --git a/samples/durable-functions/dotnet/Saga/README.md b/samples/durable-functions/dotnet/Saga/README.md index 9ab41a78..9a60962b 100644 --- a/samples/durable-functions/dotnet/Saga/README.md +++ b/samples/durable-functions/dotnet/Saga/README.md @@ -1,6 +1,6 @@ -# Order Processing with Saga Pattern in .NET 8 Durable Functions +# Order Processing with Saga Pattern in .NET 10 Durable Functions -This project demonstrates an implementation of the Saga pattern using .NET 8 and Azure Durable Functions. The Saga pattern is a failure management pattern that helps maintain data consistency across distributed business processes by defining compensating actions for each step in the workflow. +This project demonstrates an implementation of the Saga pattern using .NET 10 and Azure Durable Functions. The Saga pattern is a failure management pattern that helps maintain data consistency across distributed business processes by defining compensating actions for each step in the workflow. ## Overview @@ -65,7 +65,7 @@ For each business operation, we define a corresponding compensation: ### Prerequisites -1. [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) +1. [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) 2. [Azure Functions Core Tools](https://docs.microsoft.com/azure/azure-functions/functions-run-local) (v4.x) 3. [Docker](https://www.docker.com/products/docker-desktop/) for running the DTS emulator @@ -166,6 +166,10 @@ The emulator simulates a scheduler and taskhub in a Docker container, making it - The approval step also fails 25% of the time (by design) - When it fails, you'll see the compensation actions run in reverse order +## Telemetry + +The Functions host uses OpenTelemetry. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports to Azure Monitor. For user-assigned managed identity authentication, set `AzureMonitorExporter__credential` to `managedidentity` and `AzureMonitorExporter__clientId` to the identity's client ID, and grant that identity the Monitoring Metrics Publisher role on Application Insights. Without the connection string, the worker does not export. + ## Project Structure - **Saga/Compensations.cs** - Core compensation management logic @@ -176,6 +180,20 @@ The emulator simulates a scheduler and taskhub in a Docker container, making it ## API Reference +All three endpoints require a function or host key in Azure. Core Tools skips key enforcement locally by default, so the local examples and `test.http` work without a key. Use `func start --enableAuth` to exercise enforcement locally. + +Use a non-admin host (function) key across the starter, status, and termination endpoints; a function-specific starter key does not authorize the other functions: + +```bash +FUNCTION_KEY=$(az functionapp keys list \ + --resource-group "$AZURE_RESOURCE_GROUP" \ + --name "$AZURE_FUNCTION_NAME" --query functionKeys.default --output tsv) +curl -H "x-functions-key: ${FUNCTION_KEY}" \ + "https://${AZURE_FUNCTION_NAME}.azurewebsites.net/api/orders/${INSTANCE_ID}" +``` + +Keep the key out of source control, logs, shared output, and browser code. Do not use the master key. Keys grant application access, not order ownership or per-user authorization. The relative status URL returned by the starter does not embed a key: send the header on every status or termination request. Managed identity for DTS and telemetry is unchanged. + - **POST /api/orders** - Start a new order processing workflow - Body: Order details (customerId, productId, quantity, amount) - Returns: Instance ID and status URL diff --git a/samples/durable-functions/dotnet/Saga/host.json b/samples/durable-functions/dotnet/Saga/host.json index c0aff92f..71ed6982 100644 --- a/samples/durable-functions/dotnet/Saga/host.json +++ b/samples/durable-functions/dotnet/Saga/host.json @@ -1,5 +1,6 @@ { "version": "2.0", + "telemetryMode": "OpenTelemetry", "extensions": { "durableTask": { "hubName": "default", diff --git a/samples/durable-functions/dotnet/Saga/test.http b/samples/durable-functions/dotnet/Saga/test.http index a8215a05..2ce28819 100644 --- a/samples/durable-functions/dotnet/Saga/test.http +++ b/samples/durable-functions/dotnet/Saga/test.http @@ -1,6 +1,11 @@ +# For Azure or Core Tools --enableAuth, set this to a non-admin host key. +# Leave empty for the default local Core Tools host. Do not commit real keys. +@functionKey = + # Start a new order processing workflow # This will trigger the Saga pattern and show compensation in action POST http://localhost:7071/api/orders +x-functions-key: {{functionKey}} Content-Type: application/json { @@ -15,6 +20,8 @@ Content-Type: application/json ### Check the status of an order GET http://localhost:7071/api/orders/{{instanceId}} +x-functions-key: {{functionKey}} ### Terminate a running workflow if needed POST http://localhost:7071/api/orders/{{instanceId}}/terminate +x-functions-key: {{functionKey}} From 3ef38af391bfe2a8bc6b433f6991ec0f4830fee3 Mon Sep 17 00:00:00 2001 From: Manvir Kaur <67894494+manvkaur@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:51:27 -0800 Subject: [PATCH 3/4] Move AI travel planner changes to PR 448 Keep the AI sample and its deployment-template changes out of the .NET 10 migration PR; these changes are being carried by PR #448. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Functions/TravelPlannerOrchestrator.cs | 28 +-- .../AiAgentTravelPlanOrchestrator/Program.cs | 23 +- .../AiAgentTravelPlanOrchestrator/README.md | 62 ++---- .../TravelPlannerFunctions.csproj | 17 +- .../AiAgentTravelPlanOrchestrator/host.json | 14 +- .../infra/agent/ai-foundry-access.bicep | 28 --- .../infra/agent/ai-foundry.bicep | 104 --------- .../agent/ai-search-role-assignments.bicep | 39 ++++ .../agent/ai-service-role-assignments.bicep | 58 +++++ .../infra/agent/standard-ai-hub.bicep | 111 ++++++++++ .../infra/agent/standard-ai-project.bicep | 78 +++++++ .../agent/standard-dependent-resources.bicep | 192 ++++++++++++++++ .../infra/app/api.bicep | 2 - .../infra/app/vnet.bicep | 4 +- .../infra/core/host/functions-app.bicep | 4 +- .../infra/main.bicep | 206 +++++++++++++----- .../infra/main.parameters.json | 3 - 17 files changed, 676 insertions(+), 297 deletions(-) delete mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep delete mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep create mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep create mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep create mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep create mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep create mode 100644 samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs index ceb63ade..3d8a2d66 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Functions/TravelPlannerOrchestrator.cs @@ -9,9 +9,6 @@ namespace TravelPlannerFunctions.Functions; public class TravelPlannerOrchestrator { - // Durable custom status limit is 16 KB (UTF-16); keep headroom for serializer differences. - private const int MaxCustomStatusBytes = 15 * 1024; - private readonly ILogger _logger; public TravelPlannerOrchestrator(ILoggerFactory loggerFactory) @@ -156,33 +153,12 @@ public async Task RunTravelPlannerOrchestration( } }; - // The custom status has a max size of 16KB (UTF-16). Detailed agent output can exceed it, - // so fall back to a summary; the full plan remains available via documentUrl. + // The custom status has a max size of 16KB. var waitingStatusSize = Encoding.Unicode.GetByteCount(JsonSerializer.Serialize(waitingStatus)); logger.LogInformation("Waiting status size: {Size} bytes", waitingStatusSize); - if (waitingStatusSize <= MaxCustomStatusBytes) - { - context.SetCustomStatus(waitingStatus); - } - else - { - logger.LogWarning("Waiting status size {Size} bytes exceeds limit; sending summary status instead", waitingStatusSize); - context.SetCustomStatus(new { - waitingStatus.step, - waitingStatus.message, - waitingStatus.progress, - waitingStatus.destination, - waitingStatus.documentUrl, - travelPlan = new { - waitingStatus.travelPlan.destination, - waitingStatus.travelPlan.dates, - waitingStatus.travelPlan.cost, - waitingStatus.travelPlan.days - } - }); - } + context.SetCustomStatus(waitingStatus); approvalResponse = await context.WaitForExternalEvent( "ApprovalEvent", diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs index 0c058aea..7f5dd6e3 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/Program.cs @@ -1,5 +1,4 @@ -using Azure.Monitor.OpenTelemetry.Exporter; -using Microsoft.Azure.Functions.Worker.OpenTelemetry; +using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; @@ -7,26 +6,14 @@ using Microsoft.Extensions.Logging; using Azure.Identity; using TravelPlannerFunctions.Services; +using Azure.AI.Projects; var host = new HostBuilder() .ConfigureFunctionsWebApplication() - .ConfigureServices((context, services) => + .ConfigureServices(services => { - string? connectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]; - if (!string.IsNullOrWhiteSpace(connectionString)) - { - services.AddAzureClientsCore(); - services.AddOptions() - .Configure((options, factory) => - { - options.ConnectionString = connectionString; - options.Credential = factory.CreateTokenCredential( - context.Configuration.GetSection("AzureMonitorExporter")); - }); - services.AddOpenTelemetry() - .UseFunctionsWorkerDefaults() - .UseAzureMonitorExporter(); - } + services.AddApplicationInsightsTelemetryWorkerService(); + services.ConfigureFunctionsApplicationInsights(); services.AddLogging(); services.AddSingleton((serviceProvider) => diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md index c52734b8..052abfc3 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/README.md @@ -66,12 +66,6 @@ The complete travel plan is saved to Azure Blob Storage, and a document URL is g The travel plan is presented to the user for approval via the frontend interface. -### Travel-plan blob retention - -The sample writes documents to the private `travel-plans` container and configures no automatic expiry or cleanup job. Treat the returned blob URL as a location, not a public download link or a retention guarantee. Reading it still requires authorized storage access. - -Retain documents throughout the approval wait (up to seven days), booking/recovery, and the period during which users need to retrieve the plan or retained orchestration output. For production, choose an explicit business/privacy retention period, then delete eligible documents after those requirements end; coordinate this with durable history retention so saved URLs do not unexpectedly point to deleted plans. A lifecycle rule based only on blob age can delete a plan while approval or recovery is still pending. Account for soft-delete and version retention, which can retain data and incur charges after deletion. Deleting the dedicated sample environment removes its storage; do not delete a shared storage account to clean up travel plans. - ### Step 8: Booking Process (Conditional) If approved, the orchestrator proceeds with the booking process. If rejected, it can either terminate or restart with modified preferences. @@ -83,7 +77,7 @@ Upon successful booking, the user receives a final confirmation with all travel ## Prerequisites - Docker -- .NET 10 SDK +- .NET 8 SDK - Azure Functions Core Tools v4 - Node.js 22.12+ and npm (required by the frontend's Azure Storage and Vite dependencies) - Azure Developer CLI (azd) @@ -91,11 +85,7 @@ Upon successful booking, the user receives a final confirmation with all travel - Azure Functions resource - Azure Storage Account - Azure Durable Task resource - - Microsoft Foundry project with configured agents - -## Telemetry - -The Functions host uses OpenTelemetry. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports to Azure Monitor using the app's managed identity through `AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`. Without that connection string, the worker does not export. `AZURE_CLIENT_ID` is still required by the agent and storage clients. + - Azure AI Projects with configured agents ## Setting Up Locally @@ -120,9 +110,9 @@ Create a `local.settings.json` file in the root directory with the following con "TASKHUB_NAME": "default", "AZURE_TENANT_ID": "", "AZURE_CLIENT_ID": "", - "DESTINATION_RECOMMENDER_CONNECTION": "", - "ITINERARY_PLANNER_CONNECTION": "", - "LOCAL_RECOMMENDATIONS_CONNECTION": "", + "DESTINATION_RECOMMENDER_CONNECTION": "", + "ITINERARY_PLANNER_CONNECTION": "", + "LOCAL_RECOMMENDATIONS_CONNECTION": "", "DESTINATION_RECOMMENDER_AGENT_ID": "", "ITINERARY_PLANNER_AGENT_ID": "", "LOCAL_RECOMMENDATIONS_AGENT_ID": "" @@ -135,7 +125,7 @@ Create a `local.settings.json` file in the root directory with the following con } ``` -Replace the placeholder values with your Microsoft Foundry project endpoint and agent IDs. The `*_CONNECTION` settings must be the project endpoint URL, for example `https://.services.ai.azure.com/api/projects/`. Hub-based project connection strings (`.api.azureml.ms;...`) aren't supported by the `Azure.AI.Projects` 2.x SDK used by this sample. +Replace the placeholder values with your actual connection strings and agent IDs. ### 3. Set Up Azure Storage Emulator @@ -226,24 +216,14 @@ azd up This command will: -- Create all required Azure resources as defined in your infrastructure files, including a Microsoft Foundry resource, a Foundry project, and a `gpt-5-mini` model deployment +- Create all required Azure resources as defined in your infrastructure files - Build the backend Azure Functions - Build and deploy the frontend Vite React application -- Configure the function app with the Foundry project endpoint and grant its managed identity the **Foundry User** role (formerly **Azure AI User**) on the Foundry resource - -> [!NOTE] -> Choose `eastus2` or `swedencentral` as the location. Both regions support Durable Task Scheduler and the `gpt-5-mini` `GlobalStandard` deployment. To use a different model, set the `modelName`, `modelVersion`, `modelSkuName`, and `modelCapacity` parameters in `infra/main.bicep`. - -> [!IMPORTANT] -> By default, the Foundry resource allows public network access so that the function app can reach it. The template doesn't create a private endpoint for Foundry. To block public access, run `azd env set AI_PUBLIC_NETWORK_ACCESS Disabled` before `azd up`, and provide your own private endpoint and virtual network integration so the function app can still reach the Foundry project. -> -> The default `skipVnet=true` deployment is not a private deployment. Private Function App ingress also requires a private endpoint. The Static Web App linked backend configures Function App authentication; direct API calls must satisfy that authentication and may return 401 without it. +- Configure all connections between components ### 4. Configure AI Agents -After deployment, create the three agents in the Foundry project. You can create them in the [Foundry portal](https://ai.azure.com) or by calling the Agent Service REST API with the deployed model. The deploying user is granted the **Foundry User** role on the Foundry resource, which is required to create agents. Role assignments can take a few minutes to take effect. - -Use the following instructions for each agent: +After deployment, you'll need to set up the three AI agents in Azure AI Projects: #### Destination Recommender Agent @@ -276,31 +256,17 @@ Focus on both popular and hidden gem attractions, dining options across differen price ranges, and practical local tips that tourists wouldn't typically know. ``` -For example, the following PowerShell script creates the destination recommender agent and returns its ID. Repeat it for the other two agents with their names and instructions. - -```PowerShell -$projectEndpoint = azd env get-value PROJECT_ENDPOINT -$model = azd env get-value AI_MODEL_DEPLOYMENT_NAME -$token = az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv -$body = @{ - name = "destination-recommender" - model = $model - instructions = "You are a destination recommendation expert that helps travelers find ideal vacation spots based on their preferences, budget, and travel dates." -} | ConvertTo-Json - -$agent = Invoke-RestMethod -Method Post -Uri "$projectEndpoint/assistants?api-version=2025-05-01" ` - -Headers @{ Authorization = "Bearer $token" } -ContentType "application/json" -Body $body -$agent.id -``` - ### 5. Update Configuration -Set the agent IDs (they start with `asst_`) and reprovision to update the function app settings. The `*_CONNECTION` settings are already set to the Foundry project endpoint by the template. +Update your application settings with the proper agent connection strings and IDs: ```bash azd env set DESTINATION_RECOMMENDER_AGENT_ID "your-agent-id" azd env set ITINERARY_PLANNER_AGENT_ID "your-agent-id" azd env set LOCAL_RECOMMENDATIONS_AGENT_ID "your-agent-id" +azd env set DESTINATION_RECOMMENDER_CONNECTION "your-connection-string" +azd env set ITINERARY_PLANNER_CONNECTION "your-connection-string" +azd env set LOCAL_RECOMMENDATIONS_CONNECTION "your-connection-string" # Apply these changes to your Azure resources azd provision @@ -344,7 +310,7 @@ azd down --purge - [Azure Durable Task Scheduler](https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-durable-task-scheduler?pivots=csharp) - [Azure Durable Functions Documentation](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-overview) -- [Microsoft Foundry Agent Service Documentation](https://learn.microsoft.com/azure/ai-foundry/agents/overview) +- [Azure AI Projects Documentation](https://learn.microsoft.com/en-us/azure/ai-studio/how-to/projects-sdk-overview) - [Azure Functions Isolated Process Model](https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide) - [Azure Developer CLI Documentation](https://learn.microsoft.com/en-us/azure/developer/azure-developer-cli/) - [Azurite Emulator](https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite?tabs=visual-studio%2Cblob-storage) diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj index d9b21d1e..bef43601 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/TravelPlannerFunctions.csproj @@ -1,6 +1,6 @@ - net10.0 + net8.0 v4 Exe enable @@ -12,20 +12,19 @@ - - + + - + - - - - + + + - + diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json index 05513dd6..0b2b93eb 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/host.json @@ -1,10 +1,18 @@ { "version": "2.0", - "telemetryMode": "OpenTelemetry", "logging": { + "applicationInsights": { + "samplingSettings": { + "isEnabled": true, + "excludedTypes": "Request" + }, + "enableLiveMetricsFilters": true, + "logLevel": { + "Host.Triggers.DurableTask": "Information" + } + }, "logLevel": { - "Function": "Information", - "Host.Triggers.DurableTask": "Information" + "Function": "Information" } }, "extensions": { diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep deleted file mode 100644 index f36bde66..00000000 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry-access.bicep +++ /dev/null @@ -1,28 +0,0 @@ -// Assigns a role on the Foundry resource (AIServices account) to a principal. - -@description('Name of the Foundry resource (AIServices account)') -param aiFoundryName string - -@description('Role definition ID to assign') -param roleDefinitionID string - -@description('Principal ID to assign the role to') -param principalID string - -@description('Type of the principal') -@allowed(['User', 'ServicePrincipal', 'Group']) -param principalType string = 'ServicePrincipal' - -resource aiFoundry 'Microsoft.CognitiveServices/accounts@2025-06-01' existing = { - name: aiFoundryName -} - -resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { - name: guid(aiFoundry.id, principalID, roleDefinitionID) - scope: aiFoundry - properties: { - roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionID) - principalId: principalID - principalType: principalType - } -} diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep deleted file mode 100644 index 1e838300..00000000 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-foundry.bicep +++ /dev/null @@ -1,104 +0,0 @@ -// Creates a Microsoft Foundry resource (AIServices account), a Foundry project, and a model deployment. -// The project endpoint output is the value expected by Azure.AI.Projects 2.x (AIProjectClient). - -@description('Azure region of the Foundry resource and model deployment') -param location string - -@description('Tags to add to the resources') -param tags object = {} - -@description('Name of the Foundry resource (AIServices account). Also used as the custom subdomain.') -param aiFoundryName string - -@description('Name of the Foundry project') -param aiProjectName string - -@description('Display name of the Foundry project') -param aiProjectFriendlyName string = aiProjectName - -@description('Description of the Foundry project') -param aiProjectDescription string = '' - -@description('Model name for deployment') -param modelName string - -@description('Model format for deployment') -param modelFormat string - -@description('Model version for deployment') -param modelVersion string - -@description('Model deployment SKU name') -param modelSkuName string - -@description('Model deployment capacity') -param modelCapacity int - -@description('Whether the Foundry resource accepts traffic from public networks') -@allowed(['Enabled', 'Disabled']) -param publicNetworkAccess string = 'Enabled' - -resource aiFoundry 'Microsoft.CognitiveServices/accounts@2025-06-01' = { - name: aiFoundryName - location: location - tags: tags - kind: 'AIServices' - sku: { - name: 'S0' - } - identity: { - type: 'SystemAssigned' - } - properties: { - allowProjectManagement: true - customSubDomainName: toLower(aiFoundryName) - // The app authenticates with Microsoft Entra ID (managed identity), so keys are not needed. - disableLocalAuth: true - publicNetworkAccess: publicNetworkAccess - networkAcls: { - defaultAction: publicNetworkAccess == 'Enabled' ? 'Allow' : 'Deny' - } - } -} - -resource aiProject 'Microsoft.CognitiveServices/accounts/projects@2025-06-01' = { - parent: aiFoundry - name: aiProjectName - location: location - tags: tags - identity: { - type: 'SystemAssigned' - } - properties: { - displayName: aiProjectFriendlyName - description: aiProjectDescription - } -} - -resource modelDeployment 'Microsoft.CognitiveServices/accounts/deployments@2025-06-01' = { - parent: aiFoundry - name: modelName - sku: { - name: modelSkuName - capacity: modelCapacity - } - properties: { - model: { - name: modelName - format: modelFormat - version: modelVersion - } - } - dependsOn: [ - aiProject - ] -} - -output aiFoundryName string = aiFoundry.name -output aiFoundryId string = aiFoundry.id -output aiProjectName string = aiProject.name -output aiProjectResourceId string = aiProject.id -output aiProjectPrincipalId string = aiProject.identity.principalId -output modelDeploymentName string = modelDeployment.name -// Format: https://.services.ai.azure.com/api/projects/ -output projectEndpoint string = aiProject.properties.endpoints['AI Foundry API'] diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep new file mode 100644 index 00000000..4efab91a --- /dev/null +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-search-role-assignments.bicep @@ -0,0 +1,39 @@ +param aiSearchName string +param aiProjectPrincipalId string +param aiProjectId string + +resource searchService 'Microsoft.Search/searchServices@2024-06-01-preview' existing = { + name: aiSearchName + scope: resourceGroup() +} + +// search roles +resource searchIndexDataContributorRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { + name: '8ebe5a00-799e-43f5-93ac-243d3dce84a7' + scope: resourceGroup() +} + +resource searchIndexDataContributorAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: searchService + name: guid(aiProjectId, searchIndexDataContributorRole.id, searchService.id) + properties: { + principalId: aiProjectPrincipalId + roleDefinitionId: searchIndexDataContributorRole.id + principalType: 'ServicePrincipal' + } +} + +resource searchServiceContributorRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { + name: '7ca78c08-252a-4471-8644-bb5ff32d4ba0' + scope: resourceGroup() +} + +resource searchServiceContributorRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: searchService + name: guid(aiProjectId, searchServiceContributorRole.id, searchService.id) + properties: { + principalId: aiProjectPrincipalId + roleDefinitionId: searchServiceContributorRole.id + principalType: 'ServicePrincipal' + } +} diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep new file mode 100644 index 00000000..8cbbdf83 --- /dev/null +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/ai-service-role-assignments.bicep @@ -0,0 +1,58 @@ +// Assigns the necessary roles to the AI project + +param aiServicesName string +param aiProjectPrincipalId string +param aiProjectId string + +resource aiServices 'Microsoft.CognitiveServices/accounts@2024-06-01-preview' existing = { + name: aiServicesName + scope: resourceGroup() +} + +resource cognitiveServicesContributorRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { + name: '25fbc0a9-bd7c-42a3-aa1a-3b75d497ee68' + scope: resourceGroup() + +} + +resource cognitiveServicesContributorAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01'= { + scope: aiServices + name: guid(aiServices.id, cognitiveServicesContributorRole.id, aiProjectId) + properties: { + principalId: aiProjectPrincipalId + roleDefinitionId: cognitiveServicesContributorRole.id + principalType: 'ServicePrincipal' + } +} + +var cognitiveServicesOpenAIUserRoleId = '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' +resource cognitiveServicesOpenAIUserRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { + name: cognitiveServicesOpenAIUserRoleId + scope: resourceGroup() +} + +resource cognitiveServicesOpenAIUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: aiServices + name: guid(aiProjectId, cognitiveServicesOpenAIUserRole.id, aiServices.id) + properties: { + principalId: aiProjectPrincipalId + roleDefinitionId: cognitiveServicesOpenAIUserRole.id + principalType: 'ServicePrincipal' + } +} + +var cognitiveServiceServicesUserRoleId = 'a97b65f3-24c7-4388-baec-2e87135dc908' +resource cognitiveServicesUserRole 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = { + name: cognitiveServiceServicesUserRoleId + scope: resourceGroup() +} + +resource cognitiveServicesUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: aiServices + name: guid(aiProjectId, cognitiveServicesUserRole.id, aiServices.id) + properties: { + principalId: aiProjectPrincipalId + roleDefinitionId: cognitiveServicesUserRole.id + principalType: 'ServicePrincipal' + } +} diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep new file mode 100644 index 00000000..3c83e13e --- /dev/null +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-hub.bicep @@ -0,0 +1,111 @@ +@description('Azure region of the deployment') +param location string + +@description('Tags to add to the resources') +param tags object + +@description('AI hub name') +param aiHubName string + +@description('AI hub display name') +param aiHubFriendlyName string = aiHubName + +@description('AI hub description') +param aiHubDescription string + +@description('Resource ID of the key vault resource for storing connection strings') +param keyVaultId string + +@description('Resource ID of the storage account resource for storing experimentation outputs') +param storageAccountId string + +@description('Resource ID of the AI Services resource') +param aiServicesId string +@description('Resource ID of the AI Services endpoint') +param aiServicesTarget string +@description('Name AI Services resource') +param aiServicesName string + + +@description('Name AI Search resource') +param aiSearchName string +@description('Resource ID of the AI Search resource') +param aiSearchId string +@description('Name for capabilityHost.') +param capabilityHostName string = 'caphost1' + +var acsConnectionName = '${aiHubName}-connection-AISearch' + +var aoaiConnection = '${aiHubName}-connection-AIServices_aoai' + +resource aiServices 'Microsoft.CognitiveServices/accounts@2023-05-01' existing = { + name: aiServicesName + scope: resourceGroup() +} + +resource searchService 'Microsoft.Search/searchServices@2023-11-01' existing = { + name: aiSearchName + scope: resourceGroup() +} + +resource aiHub 'Microsoft.MachineLearningServices/workspaces@2024-07-01-preview' = { + name: aiHubName + location: location + tags: tags + identity: { + type: 'SystemAssigned' + } + properties: { + // organization + friendlyName: aiHubFriendlyName + description: aiHubDescription + + // dependent resources + keyVault: keyVaultId + storageAccount: storageAccountId + } + kind: 'hub' + + resource aiServicesConnection 'connections@2024-07-01-preview' = { + name: '${aiHubName}-connection-AIServices' + properties: { + category: 'AIServices' + target: aiServicesTarget + authType: 'AAD' + isSharedToAll: true + metadata: { + ApiType: 'Azure' + ResourceId: aiServicesId + location: aiServices.location + } + } + } + resource hub_connection_azureai_search 'connections@2024-07-01-preview' = { + name: acsConnectionName + properties: { + category: 'CognitiveSearch' + target: 'https://${aiSearchName}.search.windows.net' + authType: 'AAD' + //useWorkspaceManagedIdentity: false + isSharedToAll: true + metadata: { + ApiType: 'Azure' + ResourceId: aiSearchId + location: searchService.location + } + } + } + + // Resource definition for the capability host + resource capabilityHost 'capabilityHosts@2025-11-01' = { + name: '${aiHubName}-${capabilityHostName}' + properties: { + capabilityHostKind: 'Agents' + } + } + +} + +output aiHubID string = aiHub.id +output aoaiConnectionName string = aoaiConnection +output acsConnectionName string = acsConnectionName diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep new file mode 100644 index 00000000..a81b95d9 --- /dev/null +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-ai-project.bicep @@ -0,0 +1,78 @@ +// Creates an Azure AI resource with proxied endpoints for the Azure AI services provider + +@description('Azure region of the deployment') +param location string + +@description('Tags to add to the resources') +param tags object + +@description('AI Project name') +param aiProjectName string + +@description('AI Project display name') +param aiProjectFriendlyName string = aiProjectName + +@description('AI Project description') +param aiProjectDescription string + +@description('Resource ID of the AI Hub resource') +param aiHubId string + +@description('Name for capabilityHost.') +param capabilityHostName string = 'caphost1' + +@description('Name for ACS connection.') +param acsConnectionName string + +@description('Name for ACS connection.') +param aoaiConnectionName string + +//for constructing endpoint +var subscriptionId = subscription().subscriptionId +var resourceGroupName = resourceGroup().name + +var projectConnectionString = '${location}.api.azureml.ms;${subscriptionId};${resourceGroupName};${aiProjectName}' + + +var storageConnections = ['${aiProjectName}/workspaceblobstore'] +var aiSearchConnection = ['${acsConnectionName}'] +var aiServiceConnections = ['${aoaiConnectionName}'] + + +resource aiProject 'Microsoft.MachineLearningServices/workspaces@2023-08-01-preview' = { + name: aiProjectName + location: location + tags: union(tags, { + ProjectConnectionString: projectConnectionString + }) + identity: { + type: 'SystemAssigned' + } + properties: { + // organization + friendlyName: aiProjectFriendlyName + description: aiProjectDescription + + // dependent resources + hubResourceId: aiHubId + + } + kind: 'project' + + // Resource definition for the capability host + resource capabilityHost 'capabilityHosts@2025-11-01' = { + name: '${aiProjectName}-${capabilityHostName}' + properties: { + capabilityHostKind: 'Agents' + aiServicesConnections: aiServiceConnections + vectorStoreConnections: aiSearchConnection + storageConnections: storageConnections + } + } +} + +output aiProjectName string = aiProject.name +output aiProjectResourceId string = aiProject.id +output aiProjectPrincipalId string = aiProject.identity.principalId +output aiProjectWorkspaceId string = aiProject.properties.workspaceId +output projectConnectionString string = aiProject.tags.ProjectConnectionString diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep new file mode 100644 index 00000000..d89f7a03 --- /dev/null +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/agent/standard-dependent-resources.bicep @@ -0,0 +1,192 @@ +// Creates Azure dependent resources for Azure AI studio + +@description('Azure region of the deployment') +param location string = resourceGroup().location + +@description('Tags to add to the resources') +param tags object = {} + +@description('AI services name') +param aiServicesName string + +@description('The name of the Key Vault') +param keyvaultName string + +@description('The name of the AI Search resource') +param aiSearchName string + +@description('Name of the storage account') +param storageName string + +@description('Model name for deployment') +param modelName string + +@description('Model format for deployment') +param modelFormat string + +@description('Model version for deployment') +param modelVersion string + +@description('Model deployment SKU name') +param modelSkuName string + +@description('Model deployment capacity') +param modelCapacity int + +@description('Model/AI Resource deployment location') +param modelLocation string + +@description('The AI Service Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') +param aiServiceAccountResourceId string + +@description('The AI Search Service full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') +param aiSearchServiceResourceId string + +@description('The AI Storage Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') +param aiStorageAccountResourceId string + +var aiServiceExists = aiServiceAccountResourceId != '' +var acsExists = aiSearchServiceResourceId != '' +var aiStorageExists = aiStorageAccountResourceId != '' + +resource keyVault 'Microsoft.KeyVault/vaults@2024-12-01-preview' = { + name: keyvaultName + location: location + tags: tags + properties: { + createMode: 'default' + enabledForDeployment: false + enabledForDiskEncryption: false + enabledForTemplateDeployment: false + enableSoftDelete: true + enableRbacAuthorization: true + networkAcls: { + bypass: 'AzureServices' + defaultAction: 'Deny' + } + sku: { + family: 'A' + name: 'standard' + } + softDeleteRetentionInDays: 7 + tenantId: subscription().tenantId + } +} + + +var aiServiceParts = split(aiServiceAccountResourceId, '/') + +resource existingAIServiceAccount 'Microsoft.CognitiveServices/accounts@2023-05-01' existing = if (aiServiceExists) { + name: aiServiceParts[8] + scope: resourceGroup(aiServiceParts[2], aiServiceParts[4]) +} + +resource aiServices 'Microsoft.CognitiveServices/accounts@2024-06-01-preview' = if(!aiServiceExists) { + name: aiServicesName + location: modelLocation + sku: { + name: 'S0' + } + kind: 'AIServices' // or 'OpenAI' + identity: { + type: 'SystemAssigned' + } + properties: { + customSubDomainName: toLower('${(aiServicesName)}') + publicNetworkAccess: 'Enabled' + } +} +resource modelDeployment 'Microsoft.CognitiveServices/accounts/deployments@2024-06-01-preview'= if(!aiServiceExists){ + parent: aiServices + name: modelName + sku : { + capacity: modelCapacity + name: modelSkuName + } + properties: { + model:{ + name: modelName + format: modelFormat + version: modelVersion + } + } +} + +var acsParts = split(aiSearchServiceResourceId, '/') + +resource existingSearchService 'Microsoft.Search/searchServices@2023-11-01' existing = if (acsExists) { + name: acsParts[8] + scope: resourceGroup(acsParts[2], acsParts[4]) +} +resource aiSearch 'Microsoft.Search/searchServices@2024-06-01-preview' = if(!acsExists) { + name: aiSearchName + location: location + tags: tags + identity: { + type: 'SystemAssigned' + } + properties: { + disableLocalAuth: false + authOptions: { aadOrApiKey: { aadAuthFailureMode: 'http401WithBearerChallenge'}} + encryptionWithCmk: { + enforcement: 'Unspecified' + } + hostingMode: 'default' + partitionCount: 1 + publicNetworkAccess: 'enabled' + replicaCount: 1 + semanticSearch: 'disabled' + } + sku: { + name: 'standard' + } +} + +var aiStorageParts = split(aiStorageAccountResourceId, '/') + +resource existingAIStorageAccount 'Microsoft.Storage/storageAccounts@2023-05-01' existing = if (aiStorageExists) { + name: aiStorageParts[8] + scope: resourceGroup(aiStorageParts[2], aiStorageParts[4]) +} + +param sku string = 'Standard_LRS' + +resource storage 'Microsoft.Storage/storageAccounts@2022-05-01' = if(!aiStorageExists) { + name: storageName + location: location + kind: 'StorageV2' + sku: { + name: sku + } + properties: { + minimumTlsVersion: 'TLS1_2' + allowBlobPublicAccess: false + publicNetworkAccess: 'Enabled' + networkAcls: { + bypass: 'AzureServices' + defaultAction: 'Allow' + virtualNetworkRules: [] + } + allowSharedKeyAccess: false + } +} + +output aiServicesName string = aiServiceExists ? existingAIServiceAccount.name : aiServicesName +output aiservicesID string = aiServiceExists ? existingAIServiceAccount.id : aiServices.id +output aiservicesTarget string = aiServiceExists ? existingAIServiceAccount.properties.endpoint : aiServices.properties.endpoint +output aiServiceAccountResourceGroupName string = aiServiceExists ? aiServiceParts[4] : resourceGroup().name +output aiServiceAccountSubscriptionId string = aiServiceExists ? aiServiceParts[2] : subscription().subscriptionId + +output aiSearchName string = acsExists ? existingSearchService.name : aiSearch.name +output aisearchID string = acsExists ? existingSearchService.id : aiSearch.id +output aiSearchServiceResourceGroupName string = acsExists ? acsParts[4] : resourceGroup().name +output aiSearchServiceSubscriptionId string = acsExists ? acsParts[2] : subscription().subscriptionId + +output storageAccountName string = aiStorageExists ? existingAIStorageAccount.name : storage.name +output storageId string = aiStorageExists ? existingAIStorageAccount.id : storage.id +output storageAccountResourceGroupName string = aiStorageExists ? aiStorageParts[4] : resourceGroup().name +output storageAccountSubscriptionId string = aiStorageExists ? aiStorageParts[2] : subscription().subscriptionId + +output keyvaultId string = keyVault.id +output keyvaultUri string = keyVault.properties.vaultUri + diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep index 28ec235b..09620fe7 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/api.bicep @@ -25,8 +25,6 @@ module api '../core/host/functions-app.bicep' = { { AzureWebJobsStorage__clientId : identityClientId APPLICATIONINSIGHTS_AUTHENTICATION_STRING: applicationInsightsIdentity - AzureMonitorExporter__credential: 'managedidentity' - AzureMonitorExporter__clientId: identityClientId }) applicationInsightsName: applicationInsightsName appServicePlanId: appServicePlanId diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep index 2902467a..1a24c115 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/app/vnet.bicep @@ -52,8 +52,8 @@ resource virtualNetwork 'Microsoft.Network/virtualNetworks@2023-05-01' = { name: 'delegation' id: resourceId('Microsoft.Network/virtualNetworks/subnets/delegations', vNetName, 'app', 'delegation') properties: { - // The API runs on a dedicated (B1) App Service plan, which requires the Microsoft.Web/serverFarms delegation - serviceName: 'Microsoft.Web/serverFarms' + //Microsoft.App/environments is the correct delegation for Flex Consumption VNet integration + serviceName: 'Microsoft.App/environments' } type: 'Microsoft.Network/virtualNetworks/subnets/delegations' } diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep index 9eb0c69c..3e8a28f2 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/core/host/functions-app.bicep @@ -20,7 +20,7 @@ param kind string = 'functionapp,linux' param appSettings object = {} param allowedOrigins array = [] -var linuxFxVersion string = 'DOTNET-ISOLATED|10.0' +var linuxFxVersion string = 'DOTNET-ISOLATED|8.0' resource storageAccount 'Microsoft.Storage/storageAccounts@2024-01-01' existing = { name: storageAccountName @@ -42,7 +42,7 @@ module functions 'br/public:avm/res/web/site:0.16.0' = { userAssignedResourceIds: [identityId] } siteConfig: { - netFrameworkVersion: 'v10.0' + netFrameworkVersion: 'v8.0' linuxFxVersion: linuxFxVersion cors: { allowedOrigins: union([ 'https://portal.azure.com', 'https://ms.portal.azure.com' ], allowedOrigins) diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep index 1d59c152..8bceb3e1 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.bicep @@ -5,8 +5,8 @@ targetScope = 'subscription' param environmentName string @minLength(1) -@description('Primary location for all resources. Must support both Durable Task Scheduler and the agent model deployment.') -@allowed(['eastus2', 'swedencentral']) +@description('Primary location for all resources') +@allowed(['westus2', 'eastus', 'eastus2']) @metadata({ azd: { type: 'location' @@ -47,30 +47,41 @@ param disableLocalAuth bool = true @description('Id of the user or app to assign application roles') param principalId string = '' -@description('Name of the Microsoft Foundry resource (AIServices account). Leave empty to generate a unique name.') -param aiFoundryName string = '' +@description('Name for the AI resource and used to derive name of dependent resources.') +param aiHubName string = 'hub-demo' -@description('Name of the Microsoft Foundry project.') -param aiProjectName string = 'travel-planner' +@description('Friendly name for your Hub resource') +param aiHubFriendlyName string = 'Agents Hub resource' -@description('Display name of the Microsoft Foundry project') -param aiProjectFriendlyName string = 'Travel Planner Agents' +@description('Description of your Azure AI resource displayed in AI studio') +param aiHubDescription string = 'This is an example AI resource for use in Azure AI Studio.' -@description('Description of the Microsoft Foundry project') -param aiProjectDescription string = 'Foundry project hosting the travel planner agents.' +@description('Name for the AI project resources.') +param aiProjectName string = 'project-demo' -@description('Whether the Microsoft Foundry resource accepts traffic from public networks') -@allowed(['Enabled', 'Disabled']) -param aiPublicNetworkAccess string = 'Enabled' +@description('Friendly name for your Azure AI resource') +param aiProjectFriendlyName string = 'Agents Project resource' + +@description('Description of your Azure AI resource displayed in AI studio') +param aiProjectDescription string = 'This is an example AI Project resource for use in Azure AI Studio.' + +@description('Name of the Azure AI Search account') +param aiSearchName string = 'agentaisearch' + +@description('Name for capabilityHost.') +param capabilityHostName string = 'caphost1' + +@description('Name of the Azure AI Services account') +param aiServicesName string = 'agentaiservices' @description('Model name for deployment') -param modelName string = 'gpt-5-mini' +param modelName string = 'gpt-4o-mini' @description('Model format for deployment') param modelFormat string = 'OpenAI' @description('Model version for deployment') -param modelVersion string = '2025-08-07' +param modelVersion string = '2024-07-18' @description('Model deployment SKU name') param modelSkuName string = 'GlobalStandard' @@ -78,9 +89,18 @@ param modelSkuName string = 'GlobalStandard' @description('Model deployment capacity') param modelCapacity int = 50 -@description('Location of the Microsoft Foundry resource and model deployment, if it should differ from the rest of the resources.') +@description('Model deployment location. If you want to deploy an Azure AI resource/model in different location than the rest of the resources created.') param modelLocation string = location +@description('The AI Service Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') +param aiServiceAccountResourceId string = '' + +@description('The Ai Search Service full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') +param aiSearchServiceResourceId string = '' + +@description('The Ai Storage Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created.') +param aiStorageAccountResourceId string = '' + @description('The agent ID of the destination recommender agent') param destinationRecommenderAgentId string = 'agent-destination-recommender-agent' @@ -96,7 +116,8 @@ var resourceToken = toLower(uniqueString(subscription().id, rg.id, environmentNa var tags = { 'azd-env-name': environmentName } var functionAppName = !empty(apiServiceName) ? apiServiceName : '${abbrs.webSitesFunctions}api-${resourceToken}' var deploymentStorageContainerName = 'app-package-${take(functionAppName, 32)}-${take(toLower(uniqueString(functionAppName, resourceToken)), 7)}' -var foundryName = !empty(aiFoundryName) ? aiFoundryName : 'aif-${resourceToken}' +var name = toLower('${aiHubName}') +var projectName = toLower('${aiProjectName}') param dtsSkuName string = 'Consumption' param dtsCapacity int = 1 param dtsName string = '' @@ -107,6 +128,9 @@ var webAppName = !empty(webServiceName) ? webServiceName : '${abbrs.webStaticSit var webUri = 'https://${webAppName}.azurestaticapps.net' param webServiceName string = '' +// Create a short, unique suffix, that will be unique to each resource group +var uniqueSuffix = toLower(uniqueString(subscription().id, rg.id, location)) + // Organize resources in a resource group resource rg 'Microsoft.Resources/resourceGroups@2025-04-01' = { name: !empty(resourceGroupName) ? resourceGroupName : '${abbrs.resourcesResourceGroups}${environmentName}' @@ -194,9 +218,9 @@ module api './app/api.bicep' = { AZURE_CLIENT_ID: apiUserAssignedIdentity.outputs.identityClientId DURABLE_TASK_SCHEDULER_CONNECTION_STRING: 'Endpoint=${dts.outputs.dts_URL};Authentication=ManagedIdentity;ClientID=${apiUserAssignedIdentity.outputs.identityClientId}' TASKHUB_NAME: dts.outputs.TASKHUB_NAME - DESTINATION_RECOMMENDER_CONNECTION: aiFoundry.outputs.projectEndpoint - ITINERARY_PLANNER_CONNECTION: aiFoundry.outputs.projectEndpoint - LOCAL_RECOMMENDATIONS_CONNECTION: aiFoundry.outputs.projectEndpoint + DESTINATION_RECOMMENDER_CONNECTION: aiProject.outputs.projectConnectionString + ITINERARY_PLANNER_CONNECTION: aiProject.outputs.projectConnectionString + LOCAL_RECOMMENDATIONS_CONNECTION: aiProject.outputs.projectConnectionString DESTINATION_RECOMMENDER_AGENT_ID: destinationRecommenderAgentId ITINERARY_PLANNER_AGENT_ID: itineraryPlannerAgentId LOCAL_RECOMMENDATIONS_AGENT_ID: localRecommendationsAgentId @@ -210,49 +234,104 @@ module api './app/api.bicep' = { ] } -// Microsoft Foundry resource, project, and model deployment used by the agents -module aiFoundry './agent/ai-foundry.bicep' = { +// Dependent resources for the Azure Machine Learning workspace +module aiDependencies './agent/standard-dependent-resources.bicep' = { scope: rg - name: 'aiFoundry-${resourceToken}' + name: 'dependencies-${name}-${resourceToken}' params: { - location: modelLocation + location: location + storageName: 'st${resourceToken}' + keyvaultName: 'kv-${name}${resourceToken}' + aiServicesName: '${aiServicesName}${resourceToken}' + aiSearchName: '${aiSearchName}${resourceToken}' tags: tags - aiFoundryName: foundryName - aiProjectName: toLower(aiProjectName) - aiProjectFriendlyName: aiProjectFriendlyName - aiProjectDescription: aiProjectDescription + + // Model deployment parameters modelName: modelName modelFormat: modelFormat modelVersion: modelVersion modelSkuName: modelSkuName - modelCapacity: modelCapacity - publicNetworkAccess: aiPublicNetworkAccess + modelCapacity: modelCapacity + modelLocation: modelLocation + + aiServiceAccountResourceId: aiServiceAccountResourceId + aiSearchServiceResourceId: aiSearchServiceResourceId + aiStorageAccountResourceId: aiStorageAccountResourceId + } + + dependsOn: [ + storage + ] +} + +module aiHub './agent/standard-ai-hub.bicep' = { + scope: rg + name: '${name}-${resourceToken}' + params: { + // workspace organization + aiHubName: '${name}${uniqueSuffix}' + aiHubFriendlyName: aiHubFriendlyName + aiHubDescription: aiHubDescription + location: location + tags: tags + capabilityHostName: '${name}${uniqueSuffix}${capabilityHostName}' + + aiSearchName: aiDependencies.outputs.aiSearchName + aiSearchId: aiDependencies.outputs.aisearchID + + aiServicesName: aiDependencies.outputs.aiServicesName + aiServicesId: aiDependencies.outputs.aiservicesID + aiServicesTarget: aiDependencies.outputs.aiservicesTarget + + keyVaultId: aiDependencies.outputs.keyvaultId + storageAccountId: aiDependencies.outputs.storageId } + dependsOn: [ + storage + aiDependencies + ] } -var azureAiUserRoleId = '53ca6127-db72-4b80-b1b0-d745d6d5456d' // Foundry User (formerly Azure AI User) +module aiProject './agent/standard-ai-project.bicep' = { + scope: rg + name: '${projectName}-${resourceToken}-deployment' + params: { + // workspace organization + aiProjectName: '${projectName}${uniqueSuffix}' + aiProjectFriendlyName: aiProjectFriendlyName + aiProjectDescription: aiProjectDescription + location: location + tags: tags + + // dependent resources + capabilityHostName: '${projectName}${uniqueSuffix}${capabilityHostName}' -// Allow the function app identity to call the Foundry Agent Service -module aiFoundryRoleAssignmentApi './agent/ai-foundry-access.bicep' = { + aiHubId: aiHub.outputs.aiHubID + acsConnectionName: aiHub.outputs.acsConnectionName + aoaiConnectionName: aiHub.outputs.aoaiConnectionName + } + dependsOn:[ + storage + ] +} + +module aiServiceRoleAssignments './agent/ai-service-role-assignments.bicep' = { scope: rg - name: 'aiFoundryRoleAssignmentApi-${resourceToken}' + name: 'aiserviceroleassignments${projectName}-${resourceToken}' params: { - aiFoundryName: aiFoundry.outputs.aiFoundryName - roleDefinitionID: azureAiUserRoleId - principalID: apiUserAssignedIdentity.outputs.identityPrincipalId - principalType: 'ServicePrincipal' + aiServicesName: aiDependencies.outputs.aiServicesName + aiProjectPrincipalId: aiProject.outputs.aiProjectPrincipalId + aiProjectId: aiProject.outputs.aiProjectResourceId } } -// Allow the deploying user to create and test agents in the Foundry project -module aiFoundryRoleAssignmentUser './agent/ai-foundry-access.bicep' = if (!empty(principalId)) { +module aiSearchRoleAssignments './agent/ai-search-role-assignments.bicep' = { scope: rg - name: 'aiFoundryRoleAssignmentUser-${resourceToken}' + name: 'aisearchroleassignments${projectName}-${resourceToken}' params: { - aiFoundryName: aiFoundry.outputs.aiFoundryName - roleDefinitionID: azureAiUserRoleId - principalID: principalId - principalType: 'User' + aiSearchName: aiDependencies.outputs.aiSearchName + aiProjectPrincipalId: aiProject.outputs.aiProjectPrincipalId + aiProjectId: aiProject.outputs.aiProjectResourceId } } @@ -295,6 +374,18 @@ module storageQueueDataContributorRoleAssignmentprocessor 'app/storage-Access.bi } } +// Allow access from AI project to storage account using a managed identity +module storageQueueDataContributorRoleAssignmentAIProject 'app/storage-Access.bicep' = { + scope: rg + name: 'storageQueueDataContributorRoleAssignmentAIProject-${resourceToken}' + params: { + storageAccountName: storage.outputs.name + roleDefinitionID: storageQueueDataContributorRoleDefinitionId + principalID: aiProject.outputs.aiProjectPrincipalId + principalType: 'ServicePrincipal' + } +} + module storageQueueDataContributorRoleAssignmentUserIdentityprocessor 'app/storage-Access.bicep' = { scope: rg name: 'storageQueueDataContributorRole-${resourceToken}' @@ -371,10 +462,24 @@ module appInsightsRoleAssignmentApi './core/monitor/appinsights-access.bicep' = ] } +var azureAiDeveloperRoleId = '64702f94-c441-49e6-a78b-ef80e0188fee' // Azure AI Developer role ID +// Enable access to AI Project from the Azure Function user assigned identity +resource AIProjectRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + name: guid(azureAiDeveloperRoleId, aiProjectName, resourceId('Microsoft.MachineLearningServices/workspaces', aiProjectName), resourceToken) + properties: { + roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', azureAiDeveloperRoleId) + principalId: apiUserAssignedIdentity.outputs.identityPrincipalId + principalType: 'ServicePrincipal' + } + dependsOn: [ + apiUserAssignedIdentity + ] +} + var durableTaskDataContributorRoleDefinitionId = '0ad04412-c4d5-4796-b79c-f76d14c8d402' // Allow access from durable function to storage account using a user assigned managed identity -module dtsRoleAssignment 'app/dts-Access.bicep' = { +module dtsRoleAssignment 'app/dts-access.bicep' = { name: 'dtsRoleAssignment-${resourceToken}' scope: rg params: { @@ -390,7 +495,7 @@ module dtsRoleAssignment 'app/dts-Access.bicep' = { ] } -module dtsDashboardRoleAssignment 'app/dts-Access.bicep' = { +module dtsDashboardRoleAssignment 'app/dts-access.bicep' = { name: 'dtsDashboardRoleAssignment-${resourceToken}' scope: rg params: { @@ -435,14 +540,11 @@ output STATIC_WEB_APP_NAME string = webapp.outputs.name output STATIC_WEB_APP_URI string = webapp.outputs.uri output PRE_STATIC_WEB_APP_URI string = webAppName output RESOURCE_GROUP string = rg.name -output AI_FOUNDRY_NAME string = aiFoundry.outputs.aiFoundryName -output AI_PROJECT_NAME string = aiFoundry.outputs.aiProjectName -output AI_MODEL_DEPLOYMENT_NAME string = aiFoundry.outputs.modelDeploymentName -output PROJECT_ENDPOINT string = aiFoundry.outputs.projectEndpoint +output PROJECT_CONNECTION_STRING string = aiProject.outputs.projectConnectionString output STORAGE_CONNECTION__queueServiceUri string = 'https://${storage.outputs.name}.queue.${environment().suffixes.storage}' // Agent outputs output DESTINATION_RECOMMENDER_AGENT_ID string = destinationRecommenderAgentId output ITINERARY_PLANNER_AGENT_ID string = itineraryPlannerAgentId output LOCAL_RECOMMENDATIONS_AGENT_ID string = localRecommendationsAgentId -output AGENT_CONNECTION_STRING string = aiFoundry.outputs.projectEndpoint +output AGENT_CONNECTION_STRING string = aiProject.outputs.projectConnectionString diff --git a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json index 88ce90f6..0cf80ea9 100644 --- a/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json +++ b/samples/durable-functions/dotnet/AiAgentTravelPlanOrchestrator/infra/main.parameters.json @@ -79,9 +79,6 @@ }, "localRecommendationsAgentId": { "value": "${LOCAL_RECOMMENDATIONS_AGENT_ID}" - }, - "aiPublicNetworkAccess": { - "value": "${AI_PUBLIC_NETWORK_ACCESS=Enabled}" } } } \ No newline at end of file From 9af537082bf67c2a8fb4f48fac2f17598177e3a9 Mon Sep 17 00:00:00 2001 From: Manvir Kaur <67894494+manvkaur@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:59 -0800 Subject: [PATCH 4/4] Preserve connection-string telemetry authentication Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../durable-functions/dotnet/DistributedTracing/Program.cs | 7 +++++-- .../durable-functions/dotnet/DistributedTracing/README.md | 2 +- samples/durable-functions/dotnet/LargePayload/Program.cs | 7 +++++-- samples/durable-functions/dotnet/LargePayload/README.md | 2 +- .../dotnet/LargePayloadFanOutFanIn/Program.cs | 7 +++++-- .../dotnet/LargePayloadFanOutFanIn/README.md | 2 +- samples/durable-functions/dotnet/Saga/Program.cs | 7 +++++-- samples/durable-functions/dotnet/Saga/README.md | 2 +- 8 files changed, 24 insertions(+), 12 deletions(-) diff --git a/samples/durable-functions/dotnet/DistributedTracing/Program.cs b/samples/durable-functions/dotnet/DistributedTracing/Program.cs index 7154b6f7..f23260f1 100644 --- a/samples/durable-functions/dotnet/DistributedTracing/Program.cs +++ b/samples/durable-functions/dotnet/DistributedTracing/Program.cs @@ -18,8 +18,11 @@ .Configure((options, factory) => { options.ConnectionString = connectionString; - options.Credential = factory.CreateTokenCredential( - context.Configuration.GetSection("AzureMonitorExporter")); + var credentialSettings = context.Configuration.GetSection("AzureMonitorExporter"); + if (!string.IsNullOrWhiteSpace(context.Configuration["AzureMonitorExporter:credential"])) + { + options.Credential = factory.CreateTokenCredential(credentialSettings); + } }); services.AddOpenTelemetry() .UseFunctionsWorkerDefaults() diff --git a/samples/durable-functions/dotnet/DistributedTracing/README.md b/samples/durable-functions/dotnet/DistributedTracing/README.md index 94e9f961..210158b0 100644 --- a/samples/durable-functions/dotnet/DistributedTracing/README.md +++ b/samples/durable-functions/dotnet/DistributedTracing/README.md @@ -77,7 +77,7 @@ Distributed tracing is enabled in `host.json`: When deployed to Azure with Application Insights configured: -The Functions host uses OpenTelemetry and the Durable Task distributed tracing configuration above. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports telemetry to Azure Monitor and captures the `Microsoft.DurableTask` activity source to connect the starter to the orchestration trace. For user-assigned managed identity authentication, set `AzureMonitorExporter__credential` to `managedidentity` and `AzureMonitorExporter__clientId` to the identity's client ID, and grant that identity the Monitoring Metrics Publisher role on Application Insights. +The Functions host uses OpenTelemetry and the Durable Task distributed tracing configuration above. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports telemetry to Azure Monitor and captures the `Microsoft.DurableTask` activity source to connect the starter to the orchestration trace. For user-assigned managed identity authentication, set `AzureMonitorExporter__credential` to `managedidentity` and `AzureMonitorExporter__clientId` to the identity's client ID, and grant that identity the Monitoring Metrics Publisher role on Application Insights. If `AzureMonitorExporter__credential` is not set, the exporter uses connection-string authentication. 1. Navigate to your Application Insights resource 2. Go to **Transaction Search** diff --git a/samples/durable-functions/dotnet/LargePayload/Program.cs b/samples/durable-functions/dotnet/LargePayload/Program.cs index 064503d1..3d177e02 100644 --- a/samples/durable-functions/dotnet/LargePayload/Program.cs +++ b/samples/durable-functions/dotnet/LargePayload/Program.cs @@ -16,8 +16,11 @@ .Configure((options, factory) => { options.ConnectionString = connectionString; - options.Credential = factory.CreateTokenCredential( - context.Configuration.GetSection("AzureMonitorExporter")); + var credentialSettings = context.Configuration.GetSection("AzureMonitorExporter"); + if (!string.IsNullOrWhiteSpace(context.Configuration["AzureMonitorExporter:credential"])) + { + options.Credential = factory.CreateTokenCredential(credentialSettings); + } }); services.AddOpenTelemetry() .UseFunctionsWorkerDefaults() diff --git a/samples/durable-functions/dotnet/LargePayload/README.md b/samples/durable-functions/dotnet/LargePayload/README.md index 6ce1f9a0..145ce810 100644 --- a/samples/durable-functions/dotnet/LargePayload/README.md +++ b/samples/durable-functions/dotnet/LargePayload/README.md @@ -230,7 +230,7 @@ Core Tools normally skips HTTP key enforcement locally, so the local examples ne The Functions host uses OpenTelemetry (`telemetryMode` in `host.json`). -When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker registers OpenTelemetry and exports to Azure Monitor. The exporter authenticates with the app's managed identity through the dedicated `AzureMonitorExporter` settings (`AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`), so Application Insights local authentication can stay disabled. Without that connection string, as in local emulator runs, the worker does not export. +When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker registers OpenTelemetry and exports to Azure Monitor. The exporter authenticates with the app's managed identity through the dedicated `AzureMonitorExporter` settings (`AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`), so Application Insights local authentication can stay disabled. Unless `AzureMonitorExporter__credential` is explicitly set, the exporter uses connection-string authentication. Without that connection string, as in local emulator runs, the worker does not export. In Application Insights, inspect `requests`, `dependencies`, and `traces` for exported telemetry. Payload contents are not logged. diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs index 064503d1..3d177e02 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/Program.cs @@ -16,8 +16,11 @@ .Configure((options, factory) => { options.ConnectionString = connectionString; - options.Credential = factory.CreateTokenCredential( - context.Configuration.GetSection("AzureMonitorExporter")); + var credentialSettings = context.Configuration.GetSection("AzureMonitorExporter"); + if (!string.IsNullOrWhiteSpace(context.Configuration["AzureMonitorExporter:credential"])) + { + options.Credential = factory.CreateTokenCredential(credentialSettings); + } }); services.AddOpenTelemetry() .UseFunctionsWorkerDefaults() diff --git a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md index cf7e4790..48494b89 100644 --- a/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md +++ b/samples/durable-functions/dotnet/LargePayloadFanOutFanIn/README.md @@ -242,7 +242,7 @@ Core Tools normally skips HTTP key enforcement locally, so the local examples ne The Functions host uses OpenTelemetry (`telemetryMode` in `host.json`). -When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker registers OpenTelemetry and exports to Azure Monitor. The exporter authenticates with the app's managed identity through the dedicated `AzureMonitorExporter` settings (`AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`), so Application Insights local authentication can stay disabled. Without that connection string, as in local emulator runs, the worker does not export. +When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker registers OpenTelemetry and exports to Azure Monitor. The exporter authenticates with the app's managed identity through the dedicated `AzureMonitorExporter` settings (`AzureMonitorExporter__credential` and `AzureMonitorExporter__clientId`), so Application Insights local authentication can stay disabled. Unless `AzureMonitorExporter__credential` is explicitly set, the exporter uses connection-string authentication. Without that connection string, as in local emulator runs, the worker does not export. In Application Insights, inspect `requests`, `dependencies`, and `traces` for exported telemetry. Payload contents are not logged. diff --git a/samples/durable-functions/dotnet/Saga/Program.cs b/samples/durable-functions/dotnet/Saga/Program.cs index 0336e301..62b93163 100644 --- a/samples/durable-functions/dotnet/Saga/Program.cs +++ b/samples/durable-functions/dotnet/Saga/Program.cs @@ -16,8 +16,11 @@ .Configure((options, factory) => { options.ConnectionString = connectionString; - options.Credential = factory.CreateTokenCredential( - context.Configuration.GetSection("AzureMonitorExporter")); + var credentialSettings = context.Configuration.GetSection("AzureMonitorExporter"); + if (!string.IsNullOrWhiteSpace(context.Configuration["AzureMonitorExporter:credential"])) + { + options.Credential = factory.CreateTokenCredential(credentialSettings); + } }); services.AddOpenTelemetry() .UseFunctionsWorkerDefaults() diff --git a/samples/durable-functions/dotnet/Saga/README.md b/samples/durable-functions/dotnet/Saga/README.md index 9a60962b..34004409 100644 --- a/samples/durable-functions/dotnet/Saga/README.md +++ b/samples/durable-functions/dotnet/Saga/README.md @@ -168,7 +168,7 @@ The emulator simulates a scheduler and taskhub in a Docker container, making it ## Telemetry -The Functions host uses OpenTelemetry. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports to Azure Monitor. For user-assigned managed identity authentication, set `AzureMonitorExporter__credential` to `managedidentity` and `AzureMonitorExporter__clientId` to the identity's client ID, and grant that identity the Monitoring Metrics Publisher role on Application Insights. Without the connection string, the worker does not export. +The Functions host uses OpenTelemetry. When `APPLICATIONINSIGHTS_CONNECTION_STRING` is set, the worker exports to Azure Monitor. For user-assigned managed identity authentication, set `AzureMonitorExporter__credential` to `managedidentity` and `AzureMonitorExporter__clientId` to the identity's client ID, and grant that identity the Monitoring Metrics Publisher role on Application Insights. Unless `AzureMonitorExporter__credential` is explicitly set, the exporter uses connection-string authentication. Without the connection string, the worker does not export. ## Project Structure