diff --git a/en/labs/foundry/setup.md b/en/labs/foundry/setup.md index 66ae7d6..486df0d 100644 --- a/en/labs/foundry/setup.md +++ b/en/labs/foundry/setup.md @@ -1,182 +1,319 @@ -# Microsoft Foundry — Multi-Agent Workshop +# Microsoft Foundry — Infrastructure Intro and Setup ## Introduction -This section of the workshop covers the **reasoning and execution layer** of the Contoso Retail multi-agent architecture, implemented on **Microsoft Foundry**. This is where the intelligent agents are built: they interpret data and plan actions (executing some of them) based on the information produced by the data layer (Microsoft Fabric). +This section of the workshop covers the **reasoning and execution layer** of the Contoso Retail multi-agent architecture, implemented on **Microsoft Foundry**. Here, intelligent agents are built that interpret data and plan actions (executing some of them), based on the information generated by the data layer (Microsoft Fabric). ### Agents in this layer -| Agent | Role | Description | -|-------|------|-------------| -| **Anders** | Executor Agent | Receives requests for operational actions (such as generating reports or rendering orders) and executes them by interacting with external services like the `FxContosoRetail` Azure Function. Type: `kind: "prompt"` with an OpenAPI tool. | -| **Julie** | Planner Workflow | Orchestrates personalized marketing campaigns. Receives a customer segment description and runs a 5-step flow: (1) extracts the customer filter, (2) calls **SqlAgent** to generate T-SQL, (3) executes the query against Fabric via **Function App OpenAPI**, (4) calls **MarketingAgent** (with Bing Search) to generate per-customer messages, (5) organizes the result as a JSON email campaign. Type: `kind: "workflow"` with 3 tools (2 agents + 1 OpenAPI). | +| Agent | Role | Description | +| ---------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Anders** | Executor Agent | Receives operational action requests (such as report generation or order rendering) and executes them by interacting with external services such as the Azure Function `FxContosoRetail`. Type: `kind: "prompt"` with OpenAPI tool. | +| **Julie** | Planner Workflow | Orchestrates personalized marketing campaigns. Receives a customer segment description and executes a 5‑step flow: (1) extracts the customer filter, (2) invokes **SqlAgent** to generate T-SQL, (3) executes the query against Fabric via **Function App OpenAPI**, (4) invokes **MarketingAgent** (with Bing Search) to generate customer-specific messages, (5) organizes the result as a campaign email JSON. Type: `kind: "workflow"` with 3 tools (2 agents + 1 OpenAPI). | -### Overall architecture +### General architecture The Foundry layer sits at the center of the three-layer architecture: + ┌─────────────────────┐ + │ Copilot Studio │ ← Interaction Layer (Charles, Bill, Ric) + ├─────────────────────┤ + │ Microsoft Foundry │ ← Reasoning Layer (Anders, Julie) ★ + ├─────────────────────┤ + │ Microsoft Fabric │ ← Data Layer (Mark, Amy) + └─────────────────────┘ + +The Anders and Julie agents use GPT-4.1 models deployed in Azure AI Services to reason over business information. Anders directly consumes the `FxContosoRetail` API via an OpenAPI tool. Julie orchestrates a multi-agent workflow: it uses **SqlAgent** (generates T-SQL), a **Function App** (executes SQL against Fabric via OpenAPI), and **MarketingAgent** (generates personalized messages with Bing Search), coordinating everything autonomously as a `workflow`-type agent. + +*** + +## Setup with GitHub Codespaces + +> 💡 **Prefer to work on your local machine?** See setup.md for manual installation instructions with Azure CLI, .NET, and PowerShell 7. + +GitHub Codespaces provides a complete cloud development environment, preconfigured with all the necessary tools. You do not need to install anything on your machine — you only need a browser and access to the GitHub repository. + +> [!IMPORTANT] +> **Requirement: GitHub account** +> To use GitHub Codespaces you need a GitHub account. If you do not have one yet, you can create a free account by following the instructions at +> . + +### What does the environment include? + +| Tool | Preinstalled | +| ------------------------------- | ------------ | +| .NET 8 SDK | ✅ | +| Azure CLI (latest version) | ✅ | +| PowerShell 7+ | ✅ | +| C# Dev Kit (VS Code extension) | ✅ | +| Bicep (VS Code extension) | ✅ | +| REST Client (VS Code extension) | ✅ | + +*** + +### Step 1: Access the repository in GitHub + +1. Open your browser and navigate to the workshop GitHub repository URL provided by the instructor. +2. Sign in to GitHub. + +*** + +### Step 2: Create the Codespace + +1. On the repository main page, click the green **`< > Code`** button. + +2. Select the **Codespaces** tab. + +3. Click on **"Create codespace on main"**. + + > 💡 If you see the option to choose the machine type, the **2-core** option is more than sufficient for this workshop. + +4. Wait between **2 and 4 minutes** while GitHub builds the environment. You will see a loading screen with build logs. **This only happens the first time** — subsequent sessions start in seconds because the environment is saved. + +5. When the environment is ready, **VS Code will open in the browser** with all the repository files already available in the left panel and the .NET dependencies already restored. If the browser connection becomes unstable, it is recommended to launch the codespace in local Visual Studio Code from the Code section of the repo on GitHub: + ../../assets/codespaces-instructions.png + +> 💡 **Prefer desktop VS Code?** If you have VS Code installed on your machine with the **GitHub Codespaces** extension, you can click the `><` icon (bottom left corner) → *Connect to Codespace* to connect from local VS Code without losing the cloud environment. + +*** + +### Step 3: Verify that the environment is ready + +Open the integrated terminal with Ctrl+\` (or **Terminal → New Terminal**) and run the following three commands to confirm that everything is installed: + +```bash +dotnet --version ``` -┌─────────────────────┐ -│ Copilot Studio │ ← Interaction layer (Charles, Bill, Ric) -├─────────────────────┤ -│ Microsoft Foundry │ ← Reasoning layer (Anders, Julie) ★ -├─────────────────────┤ -│ Microsoft Fabric │ ← Data layer (Mark, Amy) -└─────────────────────┘ + +You should see something like `8.0.xxx`. + +```bash +az version ``` -The Anders and Julie agents use GPT-4.1 models deployed in Azure AI Services to reason about business information. Anders directly consumes the `FxContosoRetail` API via an OpenAPI tool. Julie orchestrates a multi-agent workflow: it uses **SqlAgent** (generates T-SQL), a **Function App** (executes the SQL against Fabric via OpenAPI), and **MarketingAgent** (generates personalized messages with Bing Search), coordinating everything autonomously as a `workflow`-type agent. +You should see the installed Azure CLI version (JSON with `"azure-cli": "2.x.x"`). ---- +```bash +pwsh --version +``` + +You should see `PowerShell 7.x.x`. + +If all three return correctly, the environment is ready for the next steps. + +*** + +### Step 4: Authenticate to Azure + +> ℹ️ **The unique suffix for your resources is automatically generated** from your Azure subscription ID (a globally unique UUID). You do not need to enter any tenant number or identifier manually. + +*** -## Infrastructure setup +In the Codespace terminal, run: -Before starting the labs, each participant must deploy the Azure infrastructure into their own subscription. The process is automated with Bicep and a PowerShell script. +```bash +az login --use-device-code +``` -### Prerequisites +> ⚠️ It is important to use `--use-device-code` in Codespaces. The normal flow (`az login`) attempts to open a local browser from the remote server, which does not work correctly in this environment. Remember that you must open the authentication URL in your local browser, where you are logged in with your lab account created for the workshop (the one ending in `@azurehol.com`). -- **Azure CLI** installed and up to date ([install](https://aka.ms/installazurecli)) +You will see an output similar to this: -- **.NET 8 SDK** installed ([download](https://dotnet.microsoft.com/download/dotnet/8.0)) + To sign in, use a web browser to open the page https://microsoft.com/devicelogin + and enter the code XXXXXXXX to authenticate. -- **PowerShell 7+** (required on all operating systems, including Windows) - - Windows: `winget install Microsoft.PowerShell` or [download MSI](https://aka.ms/powershell-release?tag=stable) - - Linux: [instructions](https://learn.microsoft.com/powershell/scripting/install/installing-powershell-on-linux) - - macOS: `brew install powershell/tap/powershell` or [instructions](https://learn.microsoft.com/powershell/scripting/install/installing-powershell-on-macos) - > ⚠️ **Important:** Run the scripts from `pwsh` (PowerShell 7), **not** from `powershell` (5.1). PowerShell 5.1 is not supported. - -- **ExecutionPolicy** configured (Windows only): To be able to run scripts from an external source such as GitHub, you need to enable this option. Open `pwsh` as administrator and run: - - ```powershell - Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser - ``` - - ✅ This is only required once. - -- An active **Azure subscription** with Owner or Contributor permissions +Follow these steps: - - Once your tenant is ready, note down the **temporary tenant number** assigned to you: if the user you were assigned is usuario@azurehol3387.com, then your tenant number is 3387. +1. Open `https://microsoft.com/devicelogin` in your browser (in a new tab). +2. Enter the 8-character code displayed in the Codespace terminal. +3. Select the **workshop Azure account** (the one ending in `@azurehol.com`). +4. Authorize access when prompted. +5. Return to the Codespace terminal — in a few seconds you will see the list of available subscriptions. -- The connection and database values from Microsoft Fabric. To obtain them, follow [this](./setup/sql-parameters.md) guide. +Verify that the active subscription is correct: +```bash +az account show --output table +``` -### ↗️ Deployment +If you need to change it: -To deploy the resources required for these labs, we have prepared Bicep and PowerShell scripts that automate the process without needing to manually create resources through the Azure or Foundry portal. +```bash +az account set --subscription "subscription-name-or-id" +``` -These scripts can be run from your local machine. However, to perform actions, you need to authenticate your local session with Azure to obtain the necessary permissions. Therefore, you must start by signing in to Azure from the terminal. +*** -1. **Open a terminal in VS Code:** use the menu **Terminal → New Terminal** or the shortcut Ctrl+`. +### Step 6: Get Microsoft Fabric parameters -2. **Sign in with Azure CLI:** +For Lab 4 (Julie/SqlAgent), you will need two values from the Fabric Warehouse: - ```powershell - az login - ``` - This will open the browser so you can authenticate with the Azure account assigned to you for the lab. Once completed, the terminal will display the list of available subscriptions. +* **FabricWarehouseSqlEndpoint**: SQL endpoint of the Warehouse, without `tcp://` or port. Example: `xyz.datawarehouse.fabric.microsoft.com` +* **FabricWarehouseDatabase**: exact and full database name. -3. **Verify the active subscription:** +To obtain them from the Fabric portal, follow the guide ./setup/sql-parameters.md. - ```powershell - az account show --output table - ``` - Confirm that the subscription shown is the correct one for the workshop. If you need to change it: - - ```powershell - az account set --subscription "subscription-name-or-id" - ``` +> **Note:** If you do not have these values yet, you can skip them. Deployment will continue without them and the rest of the infrastructure will be created correctly. You will be able to configure the SQL connection manually later from the Azure portal. -### Running the Script +*** -Once you have confirmed the login with the user corresponding to your Azure subscription, run: +### Step 7: Run the deployment script -``` powershell -cd labs\foundry\setup\op-flex -.\deploy.ps1 +In the Codespace terminal, navigate to the script folder: + +```bash +cd /workspaces/taller-multi-agentic/labs/foundry/setup/op-flex ``` -After this, the script will interactively prompt you for your deployment parameters. Press **Enter** to accept the default value for location and resource group. Here is an example of a full run: +Run the deployment script (using `pwsh` to start PowerShell 7): -``` powershell -TenantName: 3345 -Press Enter for default. -Location [eastus]: -ResourceGroupName [rg-contoso-retail]: -Do you want to configure the Fabric SQL connection for Lab04 now? (y/N): y -FabricWarehouseSqlEndpoint (no protocol, no port): kqbvkknqlijebcyrtw2rgtsx2e-dvthxhg2tsuurev2kck26gww4q.database.fabric.microsoft.com -FabricWarehouseDatabase: retail_sqldatabase_danrdol6ases3c-6d18d61e-43a5-4281-a754-b255fc9a6c9b +```bash +pwsh ./deployFromAzure.ps1 ``` -The following confirmation will be shown: +The script will only ask you for optional parameters. Press Enter to accept the default values for `Location` and `ResourceGroupName`: + + Press Enter for default. + Location ResourceGroupName [rg-contoso-retail]: + Do you want to configure the Fabric SQL connection for Lab04 now? (y/N): y + FabricWarehouseSqlEndpoint (no protocol, no port): kqbvkknqlijebcyrtw2rgtsx2e-dvthxhg2tsuurev2kck26gww4q.database.fabric.microsoft.com + FabricWarehouseDatabase: retail_sqldatabase_danrdol6ases3c-6d18d61e-43a5-4281-a754-b255fc9a6c9b + +You will see the plan confirmation before execution begins: + + ======================================== + Multi-Agent Workshop - Deployment + Plan: Flex Consumption (FC1 / Linux) + Mode: Azure Cloud Shell + ======================================== + + Subscription: My Azure Subscription (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) + Suffix: ab3f2 + Location: eastus + Resource Group: rg-contoso-retail + Fabric SQL: kqbvkknqlijebcyrtw2rgtsx2e-... + Fabric DB: retail_sqldatabase_... + +Next, you will see the deployment progress resource by resource: + + ⏳ CognitiveServices/accounts/ais-contosoretail-ab3f2 ... + ✅ Storage/storageAccounts/stcontosoretailab3f2 + ✅ Web/serverFarms/asp-contosoretail-ab3f2 + ✅ Web/sites/func-contosoretail-ab3f2 + ✅ CognitiveServices/accounts/ais-contosoretail-ab3f2 + ✅ Code published successfully. + +*** + +### Step 8: Record the deployment outputs + +At the end, write down these values from the script output: + +| Script Output | Description | Where it is used | +| ---------------------------- | --------------------------- | --------------------------------------- | +| `Unique Suffix` | 5 characters, e.g.: `ab3f2` | To identify your resources in Azure | +| `Function App Base URL` | Base URL of the API | `appsettings.json` for Anders and Julie | +| `Foundry Project Endpoint` | Foundry project endpoint | `appsettings.json` for Anders and Julie | +| `Bing Connection Name` | Bing connection name | `appsettings.json` for Julie | +| `Bing Connection ID (Julie)` | Bing connection ID | `appsettings.json` for Julie | + +*** + +### Step 9: Configure the agents' appsettings.json + +#### Anders (Lab 3) -``` powershell -======================================== - Multi-Agent Workshop - Deployment - Plan: Flex Consumption (FC1 / Linux) -======================================== +In the Codespace file panel, open: - Tenant: 3345 - Location: eastus - Resource Group: rg-contoso-retail - Fabric SQL: kqbvkknqlijebcyrtw2rgtsx2e-dvthxhg2tsuurev2kck26gww4q.database.fabric.microsoft.com - Fabric DB: retail_sqldatabase_danrdol6ases3c-6d18d61e-43a5-4281-a754-b255fc9a6c9b +`labs/foundry/code/agents/AndersAgent/ms-foundry/appsettings.json` + +Replace the `` values with the suffix obtained in the previous step: + +```json +{ + "FoundryProjectEndpoint": "https://ais-contosoretail-.services.ai.azure.com/api/projects/aip-contosoretail-", + "ModelDeploymentName": "gpt-4.1", + "FunctionAppBaseUrl": "https://func-contosoretail-.azurewebsites.net/api", + "TenantId": "" +} ``` -After this, you will start seeing the deployment progress and be informed about the resources being created. In less than 10 minutes your working environment should be fully ready. +> **TenantId**: leave it empty if you only have one active Azure account in the Codespace (the usual case). If you are working locally and have multiple tenants, enter the tenant ID of the workshop tenant: +> `bash +> az account show --query tenantId -o tsv +> ` ---- +#### Julie (Lab 4) -> 👁️ **Review the output.** When the script finishes, it displays the names and URLs of all created resources. Take note of these values — you will need them in the labs! +Open `labs/foundry/code/agents/JulieAgent/appsettings.json` and complete all values using the deployment outputs recorded in Step 8. -> **Note:** If you do not provide the Fabric parameters, the deployment **does not fail**. It skips the SQL connection configuration and shows a warning to configure it manually later. The SQL connection is only needed for Lab 5 (Julie) and the `SqlExecutor` Function App. +*** ---- +### Step 10: Assign RBAC permissions in Foundry + +For the agents to be created and executed, your user needs the **Cognitive Services User** role on the AI Services resource. Without this role, you will get a `PermissionDenied` error when attempting to create agents. -### Verification +Run these commands in the Codespace terminal (bash): + +```bash +# Get the authenticated user's Object ID (works with MSA/personal accounts and work accounts) +objectId=$(az ad signed-in-user show --query id -o tsv 2>/dev/null || \ + az account get-access-token --query accessToken -o tsv | \ + python3 -c "import sys,base64,json; t=sys.stdin.read().strip(); p=t.split('.')[1]; p+='='*(4-len(p)%4); print(json.loads(base64.b64decode(p))['oid'])") + +# Get the AI Services resource name created by the deployment +aisName=$(az cognitiveservices account list \ + --resource-group rg-contoso-retail \ + --query "[0].name" -o tsv) + +# Assign the role using the Object ID (does not require Graph API permissions) +az role assignment create \ + --assignee-object-id "$objectId" \ + --assignee-principal-type User \ + --role "Cognitive Services User" \ + --scope "/subscriptions/$(az account show --query id -o tsv)/resourceGroups/rg-contoso-retail/providers/Microsoft.CognitiveServices/accounts/$aisName" +``` -After the deployment, verify that the resources were created correctly: +Wait **1 minute** for the permission to propagate before running the agents. -```powershell +> **Note:** If you get a `RoleAssignmentExists` error, the role was already assigned automatically by the deployment script. You can continue. + +*** + +### Step 11: Verify the deployment + +Confirm that all resources were created successfully: + +```bash az resource list --resource-group rg-contoso-retail --output table ``` ---- +*** -The output should contain the following resources (names may vary): +### Codespace Management -| Resource | Name | Description | -| ------------------- | ----------------------------- | ------------------------------------------------------------ | -| Storage Account | `stcontosoretail{suffix}` | Storage for the Function App | -| App Service Plan | `asp-contosoretail-{suffix}` | Hosting plan: Flex for Azure Functions | -| Function App | `func-contosoretail-{suffix}` | Contoso Retail API (.NET 8, dotnet-isolated) | -| AI Foundry Resource | `ais-contosoretail-{suffix}` | Unified AI Foundry resource (AI Services + project management) with GPT-4.1 model deployed | -| AI Foundry Project | `aip-contosoretail-{suffix}` | Working project inside the Foundry Resource | +#### Pause (to preserve free hours) -> **Note:** The `{suffix}` is a unique 5-character identifier automatically generated from the tenant number you provided. This ensures resource names do not collide between participants. +The Codespace automatically pauses after **30 minutes of inactivity**. You can also pause it manually from the Codespaces tab in GitHub. Your files and configuration are preserved between sessions. -### RBAC permissions for Microsoft Foundry +#### Resume a saved session -For agents to be created and run in Microsoft Foundry, your user needs the **Cognitive Services User** role on the AI Services resource. This role includes the data action `Microsoft.CognitiveServices/*` required for agent operations. Without it, you will get a `PermissionDenied` error when trying to create agents. +* Go to the GitHub repository → **Code** → **Codespaces** → click on your existing Codespace. +* The environment will reopen in a few seconds with everything as you left it. +* Verify that the Azure CLI session is still active with `az account show`. If it expired, repeat Step 5. -Run the following commands to assign the role (replace `{suffix}` with your 5-character suffix): +#### Delete when the workshop is finished -```powershell -# Get your username (UPN) -$upn = az account show --query "user.name" -o tsv +To free up your quota hours: -# Assign the Cognitive Services User role on the AI Services resource -az role assignment create ` - --assignee $upn ` - --role "Cognitive Services User" ` - --scope "/subscriptions/$(az account show --query id -o tsv)/resourceGroups/rg-contoso-retail/providers/Microsoft.CognitiveServices/accounts/ais-contosoretail-{suffix}" -``` +* Go to `github.com/codespaces` +* Find your Codespace → click on `···` → **Delete**. + +> ⚠️ Deleting the Codespace will remove uncommitted local changes. If you modified the `appsettings.json` and want to keep them, copy them to a safe location before deleting. + +#### Available free hours -> **Note:** If you do not know the exact resource name, you can look it up with: -> ```powershell -> az cognitiveservices account list --resource-group rg-contoso-retail --query "[].name" -o tsv -> ``` -> -> RBAC propagation can take up to 1 minute. Wait before attempting to create agents. +GitHub offers **120 free hours/month** on 2-core machines for personal accounts. An 8‑hour workshop consumes only 7% of the monthly limit. ---