Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public async Task<HttpResponseData> GetTripConfirmationStatus(
{
if (bookingConfirmationElement.ValueKind == System.Text.Json.JsonValueKind.String)
{
string bookingConfirmation = bookingConfirmationElement.GetString();
string? bookingConfirmation = bookingConfirmationElement.GetString();
if (bookingConfirmation != null)
{
if (bookingConfirmation.Contains("Booking confirmed"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -122,7 +125,9 @@ public async Task<TravelPlanResult> RunTravelPlannerOrchestration(
documentUrl = documentUrl
});
var approvalRequest = new ApprovalRequest(context.InstanceId, travelPlan, travelRequest.UserName);
await context.CallActivityAsync(nameof(TravelPlannerActivities.RequestApproval), approvalRequest);
await context.CallActivityAsync<ApprovalRequest>(
nameof(TravelPlannerActivities.RequestApproval),
approvalRequest);

// Step 6: Wait for approval
logger.LogInformation("Step 6: Waiting for approval from user {UserName}", travelRequest.UserName);
Expand Down Expand Up @@ -153,12 +158,33 @@ public async Task<TravelPlanResult> 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<ApprovalResponse>(
"ApprovalEvent",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,38 @@
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;
using Microsoft.Extensions.Azure;
using Microsoft.Extensions.Logging;
using Azure.Identity;
using OpenTelemetry;
using OpenTelemetry.Trace;
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<AzureMonitorExporterOptions>()
.Configure<AzureComponentFactory>((options, factory) =>
{
options.ConnectionString = connectionString;
var exporterConfiguration = context.Configuration.GetSection("AzureMonitorExporter");
if (!string.IsNullOrWhiteSpace(exporterConfiguration["credential"]))
{
options.Credential = factory.CreateTokenCredential(exporterConfiguration);
}
});
services.AddOpenTelemetry()
.UseFunctionsWorkerDefaults()
Comment thread
manvkaur marked this conversation as resolved.
Resolved
.WithTracing(tracing => tracing.AddHttpClientInstrumentation())
.UseAzureMonitorExporter();
}
services.AddLogging();

services.AddSingleton<DestinationRecommenderService>((serviceProvider) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -77,15 +83,23 @@ 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)
- Azure Subscription with:
- 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. Set `APPLICATIONINSIGHTS_CONNECTION_STRING` to export worker telemetry, including outbound HTTP dependency traces, to Azure Monitor. Without the connection string, the worker does not export. When `AzureMonitorExporter__credential` is not set, the worker uses the connection string without Microsoft Entra authentication, which requires local authentication to be enabled on the Application Insights resource.

To opt in to Microsoft Entra authentication for worker telemetry, set `AzureMonitorExporter__credential` to `managedidentity` and grant the identity the Monitoring Metrics Publisher role on the Application Insights resource. For a user-assigned identity, also set `AzureMonitorExporter__clientId` to its client ID. Configure host telemetry separately with `APPLICATIONINSIGHTS_AUTHENTICATION_STRING` (for example, `Authorization=AAD;ClientId=<client-id>` for a user-assigned identity). The supplied Bicep template configures both host and worker to use its managed identity and disables local authentication by default.

`AZURE_TENANT_ID` and `AZURE_CLIENT_ID` are still required by the agent and storage setup, regardless of the telemetry authentication method.

## Setting Up Locally

Expand All @@ -110,9 +124,9 @@ Create a `local.settings.json` file in the root directory with the following con
"TASKHUB_NAME": "default",
"AZURE_TENANT_ID": "<your tenant id>",
"AZURE_CLIENT_ID": "<your client id>",
"DESTINATION_RECOMMENDER_CONNECTION": "<PROJECT_CONNECTION_STRING>",
"ITINERARY_PLANNER_CONNECTION": "<PROJECT_CONNECTION_STRING>",
"LOCAL_RECOMMENDATIONS_CONNECTION": "<PROJECT_CONNECTION_STRING>",
"DESTINATION_RECOMMENDER_CONNECTION": "<PROJECT_ENDPOINT>",
"ITINERARY_PLANNER_CONNECTION": "<PROJECT_ENDPOINT>",
"LOCAL_RECOMMENDATIONS_CONNECTION": "<PROJECT_ENDPOINT>",
"DESTINATION_RECOMMENDER_AGENT_ID": "<DESTINATION_RECOMMENDER_AGENT_ID>",
"ITINERARY_PLANNER_AGENT_ID": "<ITINERARY_PLANNER_AGENT_ID>",
"LOCAL_RECOMMENDATIONS_AGENT_ID": "<LOCAL_RECOMMENDATIONS_AGENT_ID>"
Expand All @@ -125,7 +139,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://<foundry-resource>.services.ai.azure.com/api/projects/<project>`. Hub-based project connection strings (`<region>.api.azureml.ms;...`) aren't supported by the `Azure.AI.Projects` 2.x SDK used by this sample.

### 3. Set Up Azure Storage Emulator

Expand Down Expand Up @@ -216,14 +230,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` as the location. It supports Durable Task Scheduler, Azure Static Web Apps, and `gpt-5-mini` `GlobalStandard` for Foundry Agent Service. 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

Expand Down Expand Up @@ -256,17 +280,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
Expand Down Expand Up @@ -310,7 +348,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)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
Expand All @@ -12,19 +12,21 @@
<PackageReference Include="Azure.AI.Projects" Version="2.0.1" />
<PackageReference Include="Azure.AI.Agents.Persistent" Version="1.1.0" />
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.30.0" />
<PackageReference Include="Azure.Storage.Queues" Version="12.28.0" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.30.1" />
<PackageReference Include="Azure.Storage.Queues" Version="12.28.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.52.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.DurableTask.AzureManaged" Version="1.10.2" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.DurableTask.AzureManaged" Version="1.12.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.3.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.1.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage.Queues" Version="5.5.5" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.1.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="3.1.2" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="2.51.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.DurableTask" Version="1.19.2" />
<PackageReference Include="Azure.Monitor.OpenTelemetry.Exporter" Version="1.10.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.OpenTelemetry" Version="1.2.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.20.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.20.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.DurableTask" Version="1.22.0" />
<PackageReference Include="Contrib.Grpc.Core.M1" Version="2.46.7" />
<PackageReference Include="Grpc.Net.Client" Version="2.84.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.85.0" />
<PackageReference Include="Microsoft.Extensions.Azure" Version="1.14.1" />
</ItemGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
}
Loading
Loading