From 0aa09cf9ae27a8694a0f281fc5bbd738c2218b37 Mon Sep 17 00:00:00 2001 From: "foundry-samples-repo-sync[bot]" Date: Sat, 14 Feb 2026 06:16:15 +0000 Subject: [PATCH] Sync from private repository (2026-02-14) --- .pre-commit-config.yaml | 4 + .../azuredeploy.json | 122 +++-- .../reinforcement/data/rft_training_set.jsonl | 100 +++++ .../data/rft_validation_set.jsonl | 10 + .../reinforcement/sample_finetuning_rft.yaml | 22 + .../Evaluate/Evaluate.csproj | 10 +- .../1-idea-to-prototype/Evaluate/Program.cs | 421 ++++++------------ .../1-idea-to-prototype/Evaluate/nuget.config | 3 +- .../ModernWorkplaceAssistant/nuget.config | 3 +- .../shared/questions.jsonl | 2 + .../AgentThreadAndHITL.csproj | 21 + .../AgentThreadAndHITL/Dockerfile | 20 + .../AgentThreadAndHITL/Program.cs | 42 ++ .../AgentThreadAndHITL/README.md | 104 +++++ .../AgentThreadAndHITL/agent.yaml | 29 ++ .../AgentThreadAndHITL/test_requests.py | 67 +++ .../AgentWithHostedMCP.csproj | 2 +- .../AgentWithTextSearchRag.csproj | 2 +- .../AgentWithTools/AgentWithTools.csproj | 2 +- .../AgentsInWorkflows.csproj | 4 +- .../AgentsInWorkflows/Program.cs | 21 +- .../SystemUtilityAgent.csproj | 4 +- samples/csharp/quickstart/AgentService.cs | 39 +- samples/csharp/quickstart/nuget.config | 1 + .../quickstart/quickstart-create-agent.cs | 9 +- .../csharp/quickstart/quickstart-responses.cs | 13 +- .../agent-with-foundry-tools/agent.yaml | 2 +- .../agent-with-foundry-tools/main.py | 11 +- .../agent-with-foundry-tools/requirements.txt | 2 +- .../agent-with-local-tools/requirements.txt | 2 +- .../agent-with-text-search-rag/main.py | 12 +- .../requirements.txt | 2 +- .../agents-in-workflow/main.py | 15 +- .../agents-in-workflow/requirements.txt | 2 +- .../echo-agent/requirements.txt | 2 +- .../agent-with-thread-and-hitl/main.py | 10 +- .../requirements.txt | 2 +- .../main.py | 10 +- .../requirements.txt | 2 +- .../web-search-agent/requirements.txt | 2 +- .../system-utility-agent/requirements.txt | 2 +- .../calculator-agent/requirements.txt | 2 +- .../human-in-the-loop/requirements.txt | 2 +- .../requirements.txt | 2 +- 44 files changed, 757 insertions(+), 404 deletions(-) create mode 100644 samples/cli/finetuning/reinforcement/data/rft_training_set.jsonl create mode 100644 samples/cli/finetuning/reinforcement/data/rft_validation_set.jsonl create mode 100644 samples/cli/finetuning/reinforcement/sample_finetuning_rft.yaml create mode 100644 samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/shared/questions.jsonl create mode 100644 samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/AgentThreadAndHITL.csproj create mode 100644 samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Dockerfile create mode 100644 samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Program.cs create mode 100644 samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/README.md create mode 100644 samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/agent.yaml create mode 100644 samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/test_requests.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 38c389d44..6d2de6e05 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -5,6 +5,10 @@ repos: rev: v3.2.0 hooks: - id: check-added-large-files +- repo: https://github.com/rhysd/actionlint + rev: v1.7.7 + hooks: + - id: actionlint - repo: local hooks: - id: nb-clean diff --git a/infrastructure/infrastructure-setup-bicep/15-private-network-standard-agent-setup/azuredeploy.json b/infrastructure/infrastructure-setup-bicep/15-private-network-standard-agent-setup/azuredeploy.json index fd1247d0f..8c09508fa 100644 --- a/infrastructure/infrastructure-setup-bicep/15-private-network-standard-agent-setup/azuredeploy.json +++ b/infrastructure/infrastructure-setup-bicep/15-private-network-standard-agent-setup/azuredeploy.json @@ -4,8 +4,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "16616047834738415823" + "version": "0.40.2.10011", + "templateHash": "10213309447334439675" } }, "parameters": { @@ -178,6 +178,13 @@ "description": "The Cosmos DB Account full ARM Resource ID. This is an optional field, and if not provided, the resource will be created." } }, + "dnsZonesSubscriptionId": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Subscription ID where existing private DNS zones are located. Leave empty to use current subscription." + } + }, "existingDnsZones": { "type": "object", "defaultValue": { @@ -238,7 +245,8 @@ "vnetSubscriptionId": "[if(variables('existingVnetPassedIn'), variables('vnetParts')[2], subscription().subscriptionId)]", "vnetResourceGroupName": "[if(variables('existingVnetPassedIn'), variables('vnetParts')[4], resourceGroup().name)]", "existingVnetName": "[if(variables('existingVnetPassedIn'), last(variables('vnetParts')), parameters('vnetName'))]", - "trimVnetName": "[trim(variables('existingVnetName'))]" + "trimVnetName": "[trim(variables('existingVnetName'))]", + "resolvedDnsZonesSubscriptionId": "[if(empty(parameters('dnsZonesSubscriptionId')), subscription().subscriptionId, parameters('dnsZonesSubscriptionId'))]" }, "resources": [ { @@ -288,8 +296,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "8505298823279202405" + "version": "0.40.2.10011", + "templateHash": "9522150535342725348" } }, "parameters": { @@ -402,8 +410,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "4954184648131521061" + "version": "0.40.2.10011", + "templateHash": "1725519900292599397" } }, "parameters": { @@ -575,8 +583,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "3152324712046183852" + "version": "0.40.2.10011", + "templateHash": "12834877200138369468" } }, "parameters": { @@ -665,8 +673,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "17043822047386586435" + "version": "0.40.2.10011", + "templateHash": "16684585228229443328" } }, "parameters": { @@ -748,8 +756,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "17043822047386586435" + "version": "0.40.2.10011", + "templateHash": "16684585228229443328" } }, "parameters": { @@ -920,8 +928,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "854097619778148359" + "version": "0.40.2.10011", + "templateHash": "481468620289904255" } }, "parameters": { @@ -1049,6 +1057,9 @@ }, "dnsZoneNames": { "value": "[parameters('dnsZoneNames')]" + }, + "dnsZonesSubscriptionId": { + "value": "[variables('resolvedDnsZonesSubscriptionId')]" } }, "template": { @@ -1057,8 +1068,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "7641310640078958122" + "version": "0.40.2.10011", + "templateHash": "13265653374239491155" } }, "parameters": { @@ -1086,6 +1097,12 @@ "description": "Object mapping DNS zone names to their resource group, or empty string to indicate creation" } }, + "dnsZonesSubscriptionId": { + "type": "string", + "metadata": { + "description": "Subscription ID where existing private DNS zones are located. Should be resolved to current subscription if empty." + } + }, "dnsZoneNames": { "type": "array", "metadata": { @@ -1209,8 +1226,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "2754228344238136934" + "version": "0.40.2.10011", + "templateHash": "1228922674432785221" } }, "parameters": { @@ -1481,6 +1498,9 @@ }, "existingDnsZones": { "value": "[parameters('existingDnsZones')]" + }, + "dnsZonesSubscriptionId": { + "value": "[variables('resolvedDnsZonesSubscriptionId')]" } }, "template": { @@ -1489,8 +1509,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "8094529554453089222" + "version": "0.40.2.10011", + "templateHash": "6108847882161636110" } }, "parameters": { @@ -1605,6 +1625,12 @@ "metadata": { "description": "Map of DNS zone FQDNs to resource group names. If provided, reference existing DNS zones in this resource group instead of creating them." } + }, + "dnsZonesSubscriptionId": { + "type": "string", + "metadata": { + "description": "Subscription ID where existing private DNS zones are located. Should be resolved to current subscription if empty." + } } }, "variables": { @@ -1620,12 +1646,12 @@ "aiSearchDnsZoneRG": "[parameters('existingDnsZones')[variables('aiSearchDnsZoneName')]]", "storageDnsZoneRG": "[parameters('existingDnsZones')[variables('storageDnsZoneName')]]", "cosmosDBDnsZoneRG": "[parameters('existingDnsZones')[variables('cosmosDBDnsZoneName')]]", - "aiServicesDnsZoneId": "[if(empty(variables('aiServicesDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('aiServicesDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, variables('aiServicesDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('aiServicesDnsZoneName')))]", - "openAiDnsZoneId": "[if(empty(variables('openAiDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('openAiDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, variables('openAiDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('openAiDnsZoneName')))]", - "cognitiveServicesDnsZoneId": "[if(empty(variables('cognitiveServicesDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('cognitiveServicesDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, variables('cognitiveServicesDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('cognitiveServicesDnsZoneName')))]", - "aiSearchDnsZoneId": "[if(empty(variables('aiSearchDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('aiSearchDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, variables('aiSearchDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('aiSearchDnsZoneName')))]", - "storageDnsZoneId": "[if(empty(variables('storageDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('storageDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, variables('storageDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('storageDnsZoneName')))]", - "cosmosDBDnsZoneId": "[if(empty(variables('cosmosDBDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('cosmosDBDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, variables('cosmosDBDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('cosmosDBDnsZoneName')))]" + "aiServicesDnsZoneId": "[if(empty(variables('aiServicesDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('aiServicesDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', parameters('dnsZonesSubscriptionId'), variables('aiServicesDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('aiServicesDnsZoneName')))]", + "openAiDnsZoneId": "[if(empty(variables('openAiDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('openAiDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', parameters('dnsZonesSubscriptionId'), variables('openAiDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('openAiDnsZoneName')))]", + "cognitiveServicesDnsZoneId": "[if(empty(variables('cognitiveServicesDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('cognitiveServicesDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', parameters('dnsZonesSubscriptionId'), variables('cognitiveServicesDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('cognitiveServicesDnsZoneName')))]", + "aiSearchDnsZoneId": "[if(empty(variables('aiSearchDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('aiSearchDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', parameters('dnsZonesSubscriptionId'), variables('aiSearchDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('aiSearchDnsZoneName')))]", + "storageDnsZoneId": "[if(empty(variables('storageDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('storageDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', parameters('dnsZonesSubscriptionId'), variables('storageDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('storageDnsZoneName')))]", + "cosmosDBDnsZoneId": "[if(empty(variables('cosmosDBDnsZoneRG')), resourceId('Microsoft.Network/privateDnsZones', variables('cosmosDBDnsZoneName')), extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', parameters('dnsZonesSubscriptionId'), variables('cosmosDBDnsZoneRG')), 'Microsoft.Network/privateDnsZones', variables('cosmosDBDnsZoneName')))]" }, "resources": [ { @@ -2018,8 +2044,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "5095087340309076800" + "version": "0.40.2.10011", + "templateHash": "1007872875847158534" } }, "parameters": { @@ -2193,8 +2219,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "6910483561575524105" + "version": "0.40.2.10011", + "templateHash": "12606978205101260380" } }, "parameters": { @@ -2248,8 +2274,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "14683840003859985069" + "version": "0.40.2.10011", + "templateHash": "15991712531324316353" } }, "parameters": { @@ -2264,7 +2290,7 @@ { "type": "Microsoft.Authorization/roleAssignments", "apiVersion": "2022-04-01", - "scope": "[format('Microsoft.Storage/storageAccounts/{0}', parameters('azureStorageName'))]", + "scope": "[resourceId('Microsoft.Storage/storageAccounts', parameters('azureStorageName'))]", "name": "[guid(parameters('projectPrincipalId'), resourceId('Microsoft.Authorization/roleDefinitions', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe'), resourceId('Microsoft.Storage/storageAccounts', parameters('azureStorageName')))]", "properties": { "principalId": "[parameters('projectPrincipalId')]", @@ -2306,8 +2332,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "25128059954858801" + "version": "0.40.2.10011", + "templateHash": "7256419427588810161" } }, "parameters": { @@ -2328,7 +2354,7 @@ { "type": "Microsoft.Authorization/roleAssignments", "apiVersion": "2022-04-01", - "scope": "[format('Microsoft.DocumentDB/databaseAccounts/{0}', parameters('cosmosDBName'))]", + "scope": "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('cosmosDBName'))]", "name": "[guid(parameters('projectPrincipalId'), resourceId('Microsoft.Authorization/roleDefinitions', '230815da-be43-4aae-9cb4-875f7bd000aa'), resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('cosmosDBName')))]", "properties": { "principalId": "[parameters('projectPrincipalId')]", @@ -2370,8 +2396,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "7968115481508840" + "version": "0.40.2.10011", + "templateHash": "15867124606695536257" } }, "parameters": { @@ -2392,7 +2418,7 @@ { "type": "Microsoft.Authorization/roleAssignments", "apiVersion": "2022-04-01", - "scope": "[format('Microsoft.Search/searchServices/{0}', parameters('aiSearchName'))]", + "scope": "[resourceId('Microsoft.Search/searchServices', parameters('aiSearchName'))]", "name": "[guid(parameters('projectPrincipalId'), resourceId('Microsoft.Authorization/roleDefinitions', '8ebe5a00-799e-43f5-93ac-243d3dce84a7'), resourceId('Microsoft.Search/searchServices', parameters('aiSearchName')))]", "properties": { "principalId": "[parameters('projectPrincipalId')]", @@ -2403,7 +2429,7 @@ { "type": "Microsoft.Authorization/roleAssignments", "apiVersion": "2022-04-01", - "scope": "[format('Microsoft.Search/searchServices/{0}', parameters('aiSearchName'))]", + "scope": "[resourceId('Microsoft.Search/searchServices', parameters('aiSearchName'))]", "name": "[guid(parameters('projectPrincipalId'), resourceId('Microsoft.Authorization/roleDefinitions', '7ca78c08-252a-4471-8644-bb5ff32d4ba0'), resourceId('Microsoft.Search/searchServices', parameters('aiSearchName')))]", "properties": { "principalId": "[parameters('projectPrincipalId')]", @@ -2455,8 +2481,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "17458377866351620215" + "version": "0.40.2.10011", + "templateHash": "687161311666023487" } }, "parameters": { @@ -2549,8 +2575,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "13874725855824693255" + "version": "0.40.2.10011", + "templateHash": "3625425571119261380" } }, "parameters": { @@ -2580,7 +2606,7 @@ { "type": "Microsoft.Authorization/roleAssignments", "apiVersion": "2022-04-01", - "scope": "[format('Microsoft.Storage/storageAccounts/{0}', parameters('storageName'))]", + "scope": "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageName'))]", "name": "[guid(resourceId('Microsoft.Authorization/roleDefinitions', 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b'), resourceId('Microsoft.Storage/storageAccounts', parameters('storageName')))]", "properties": { "principalId": "[parameters('aiProjectPrincipalId')]", @@ -2628,8 +2654,8 @@ "metadata": { "_generator": { "name": "bicep", - "version": "0.39.26.7824", - "templateHash": "17187611271934567223" + "version": "0.40.2.10011", + "templateHash": "14722474518981746838" } }, "parameters": { diff --git a/samples/cli/finetuning/reinforcement/data/rft_training_set.jsonl b/samples/cli/finetuning/reinforcement/data/rft_training_set.jsonl new file mode 100644 index 000000000..df428dd02 --- /dev/null +++ b/samples/cli/finetuning/reinforcement/data/rft_training_set.jsonl @@ -0,0 +1,100 @@ +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nCall a scalene triangle K [i]disguisable[/i] if there exists a triangle K′ similar to K with two shorter sides precisely as long as the two longer sides of K, respectively. Call a disguisable triangle [i]integral[/i] if the lengths of all its sides are integers.\r\n(a) Find the side lengths of the integral disguisable triangle with the smallest possible perimeter.\r\n(b) Let K be an arbitrary integral disguisable triangle for which no smaller integral\r\ndisguisable triangle similar to it exists. Prove that at least two side lengths of K are\r\nperfect squares.", "role": "user"}], "answer": "9"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n11. A math competition problem: the probabilities of A, B, and C solving this problem independently are $\\frac{1}{a}$, $\\frac{1}{b}$, and $\\frac{1}{c}$, respectively, where $a$, $b$, and $c$ are positive integers less than 10. Now A, B, and C are solving this problem independently. If the probability that exactly one of them solves the problem is $\\frac{7}{15}$, then the probability that none of them solves the problem is", "role": "user"}], "answer": "\\dfrac{4"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n8 There are six cards, each with a number $1, 2, 3, 4, 5, 6$ written on it. Each time, one card is drawn, the number on it is noted, and then it is put back. This is done 4 times. The probability that the difference between the maximum and minimum numbers drawn is equal to 5 is $\\qquad$.", "role": "user"}], "answer": "\\dfrac{151"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n5th Swedish 1965 Problem 2 Find all positive integers m, n such that m 3 - n 3 = 999.", "role": "user"}], "answer": "(12, 9)"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n\n5. Given three positive real numbers $o, \\rho, v$, construct a triangle $A B C$ with perimeter equal to $o$, the radius of its $A$-excircle equal to $\\rho$, and the length of its $A$ altitude equal to $v$. Determine the number of solutions (non-congruent triangles) in terms of the given lengths.\n\n(Patrik Bak)\n", "role": "user"}], "answer": "0"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n3. In the afternoon, 5 classes need to be scheduled: Physics, Chemistry, Biology, and two self-study periods. If the first class cannot be Biology and the last class cannot be Physics, then the number of different scheduling methods is ( ) kinds.\n(A) 36\n(B) 39\n(C) 60\n(D) 78", "role": "user"}], "answer": "B"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n9. A, B, C, and D are comparing their heights. Among them, the sum of the heights of two people is the same as the sum of the heights of the other two. The average height of A and B is 4 cm more than the average height of A and C. D is 10 cm taller than A, and the sum of the heights of B and C is 288 cm. A's height is $\\qquad$ cm.", "role": "user"}], "answer": "139"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n1. Solve the equation $x^{\\log _{5}(0.008 x)}=\\frac{125}{x^{5}}$.", "role": "user"}], "answer": "\\dfrac{1"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n4.9 If $b0\n$$", "role": "user"}], "answer": "1, 2, 3, 4, 5, 6, 7"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nGiven $\\triangle A B C$ has a perimeter of 20, area of $01 \\sqrt{3}$, and $\\angle A=60^{\\circ}$. Find $\\sin A: \\sin B: \\sin C$.", "role": "user"}], "answer": "7:8:5"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nB2 Points $A(-4,-2), B(2,-2)$ and $C(2,6)$ are the vertices of triangle $A B C$.\n\nA Draw triangle $A B C$ in the coordinate system.\n\nB Calculate the perimeter of triangle $A B C$.\n\nC Calculate the area of triangle $A B C$.\n\nD Circumscribe a circle around triangle $A B C$.", "role": "user"}], "answer": "(x + 1)^2 + (y - 2)^2 = 25"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n【Question 1】Calculate: $2 \\times(999999+5 \\times 379 \\times 4789)=$", "role": "user"}], "answer": "20150308"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n2. Simplify the expression\n\n$$\nA=\\left(1+\\frac{1+i}{2}\\right)\\left(1+\\left(\\frac{1+i}{2}\\right)^{2}\\right)\\left(1+\\left(\\frac{1+i}{2}\\right)^{4}\\right)\\left(1+\\left(\\frac{1+i}{2}\\right)^{8}\\right)\n$$\n\n( $i$ is the imaginary unit)", "role": "user"}], "answer": "\\dfrac{255(1 + i)"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nExample 3 (1) Find the domain of the function $y=\\sqrt{\\frac{1}{2}-\\log _{2}(3-x)}$;\n(2) Given that the domain of $f(x)$ is $[0,1]$, find the domain of the function $y=f\\left(\\log _{\\frac{1}{2}}(3-x)\\right)$.", "role": "user"}], "answer": "[2, \\frac{5"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n8. As shown in Figure $3, A C=$ $B C, A C \\perp B C$ at point $C, A B=A D=B D$, $C D=C E=D E$. If $A B=\\sqrt{2}$, then $B E=$", "role": "user"}], "answer": "1"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nAt each vertex of a tetrahedron, there sits an ant. At a given moment, each of them starts to move along a randomly chosen edge and crosses over to the adjacent vertex. What is the probability that two ants meet either on the way or at the end of their journey?", "role": "user"}], "answer": "\\dfrac{25"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n7. A turtle and a rabbit are in a 1000-meter race. The rabbit took a nap 200 meters from the finish line. When it woke up, it found that the turtle was 10 meters from the finish line, so it immediately chased after and eventually both reached the finish line at the same time. If the turtle crawled at a constant speed throughout the race, and the rabbit's speed before and after the nap was the same, then, during the rabbit's nap, the turtle crawled $\\qquad$ meters.", "role": "user"}], "answer": "950"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nWe are given 5771 weights weighing 1,2,3,...,5770,5771. We partition the weights into $n$ sets of equal weight. What is the maximal $n$ for which this is possible?", "role": "user"}], "answer": "2886"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n7. As shown in the figure, the beads on the bracelet are numbered from 1 to 22 in a counterclockwise direction starting from the pendant bead. Xiao Ming is playing a bead counting game, with the rule being: starting from bead 1, count natural numbers in a clockwise direction, but skip any number that contains the digit 7 or is a multiple of 7, and directly count the next number. For example: after counting to 6, the next number is 8; after counting to 13, the next number is 15, and so on. So, when counting to 100, which bead number $\\qquad$ will it land on?", "role": "user"}], "answer": "19"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nLet $ABC$ be a triangle and let $P$ be a point in its interior. Suppose $ \\angle B A P = 10 ^ { \\circ } , \\angle A B P = 20 ^ { \\circ } , \\angle P C A = 30 ^ { \\circ } $ and $ \\angle P A C = 40 ^ { \\circ } $. Find $ \\angle P B C $.", "role": "user"}], "answer": "60^\\circ"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n(2) In the Cartesian coordinate system $x O y$, the area of the figure enclosed by the curve $2|x|+3|y|=5$ is ( ).\n(A) $\\frac{5}{3}$\n(B) 5\n(C) $\\frac{20}{3}$\n(D) $\\frac{25}{3}$", "role": "user"}], "answer": "D"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nGiven a digits {$0,1,2,...,9$} . Find the number of numbers of 6 digits which cantain $7$ or $7$'s digit and they is permulated(For example 137456 and 314756 is one numbers).", "role": "user"}], "answer": "2002"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n[ Skeletons of Polyhedral Figures ]\n\nA toy factory produces wireframe cubes, with small colorful beads located at their vertices. According to the GOST standard, each cube must use beads of all eight colors (white and the seven colors of the rainbow). How many different models of cubes can the factory produce?\n\n#", "role": "user"}], "answer": "1680"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n## Problem Statement\n\nCalculate the limit of the function:\n\n$\\lim _{x \\rightarrow 0} \\frac{6^{2 x}-7^{-2 x}}{\\sin 3 x-2 x}$", "role": "user"}], "answer": "2 \\ln 42"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nG5.3 If $R^{2000}<5^{3000}$, where $R$ is a positive integer, find the largest value of $R$.", "role": "user"}], "answer": "11"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n## Task 18/78\n\nDetermine the greatest common divisor of all numbers $z$ that can be represented in the form $z=n^{4 m+1}-n$ with $m ; n \\in N$!", "role": "user"}], "answer": "30"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nWhich is the two-digit number that, when divided by the digit in the units place, gives a quotient of 9 and a remainder of 6?", "role": "user"}], "answer": "78"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n5. In $\\triangle A B C$, medians $A D$ and $C F$ intersect at point $G$. If $\\angle A F G=45^{\\circ}, \\angle A G C=60^{\\circ}$, then the degree measure of $\\angle A C F$ is ( ).\n(A) $30^{\\circ}$\n(B) $45^{\\circ}$\n(C) $60^{\\circ}$\n(D) $75^{\\circ}$", "role": "user"}], "answer": "D"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nFind the maximum positive integer $k$ such that for any positive integers $m,n$ such that $m^3+n^3>(m+n)^2$, we have\n\n$$m^3+n^3\\geq (m+n)^2+k$$\n\n[i] Proposed by Dorlir Ahmeti, Albania[/i]", "role": "user"}], "answer": "10"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n11. Choose three different digits from $0,1, \\cdots, 9$ to form a four-digit number (one of the digits can appear twice), such as 5 224. Then the total number of such four-digit numbers is $\\qquad$.", "role": "user"}], "answer": "3888"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n2. The three sides of a triangle $a, b, c$ are all integers, and satisfy $a b c + b c + c a + a b + a + b + c = 7$. Then the area of the triangle is equal to ().\n(A) $\\frac{\\sqrt{3}}{2}$\n(B) $\\frac{\\sqrt{2}}{4}$\n(C) $\\frac{\\sqrt{3}}{4}$\n(D) $\\frac{\\sqrt{2}}{2}$", "role": "user"}], "answer": "C"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n## Task Condition\n\nFind the point $M^{\\prime}$ symmetric to the point $M$ with respect to the line.\n\n$M(2 ; 1 ; 0)$\n\n$\\frac{x-2}{0}=\\frac{y+1.5}{-1}=\\frac{z+0.5}{1}$", "role": "user"}], "answer": "(2, -2, -3)"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nA number is called Norwegian if it has three distinct positive divisors whose sum is equal to 2022. Determine the smallest Norwegian number. (Note: The total number of positive divisors of a Norwegian number is allowed to be larger than 3.) (Cyprus) Answer: 1344", "role": "user"}], "answer": "1344"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nB5. My 24-hour digital clock displays hours and minutes only.\nFor how many different times does the display contain at least one occurrence of the digit 5 in a 24-hour period?", "role": "user"}], "answer": "450"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n17.51 In $\\triangle A B C$, $A C: C B=3: 4, \\angle C$'s exterior angle bisector intersects the extension of $B A$ at $P$ ($A$ is between $P$ and $B$), then $P A: A B$ is\n(A) $1: 3$.\n(B) $3: 4$.\n(C) $4: 3$.\n(D) $3: 1$.\n(E) $7: 1$.\n(12th American High School Mathematics Examination, 1961)", "role": "user"}], "answer": "D"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n7. The program flowchart is shown in Figure 3. Given that the real number $x \\in [1, 9]$. Then the probability that the output $x$ is not less than 55 is ( ).\n(A) $\\frac{1}{3}$\n(B) $\\frac{2}{3}$\n(C) $\\frac{3}{8}$\n(D) $\\frac{5}{8}$", "role": "user"}], "answer": "D"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n18. There are 30 students standing in a row, and from left to right, they are wearing hats in the order of \"red, yellow, blue, red, yellow, blue......\". The PE teacher asks the students to count off from left to right as \"1, 2, 1, 2, 1, 2.....\", and those who count off 2 step forward. Among the remaining students, those wearing red hats step back. At this point, the students are divided into 3 rows, and in the middle row, there are $\\qquad$ people wearing blue hats.", "role": "user"}], "answer": "5"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n1. 19 If $\\frac{1}{x}+\\frac{1}{y}+\\frac{1}{z}=\\frac{1}{x+y+z}=1$. Then,\n(A) at least one of $x, y, z$ is equal to 1.\n(B) $x, y, z$ are all equal to 1.\n(C) $x, y, z$ are all not equal to 1.\n(D) none of the above conclusions is correct.\n(8th \"Jinyun Cup\" Junior High School Mathematics Invitational, 1991)", "role": "user"}], "answer": "A"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n3. Let $x_{1}$ and $x_{2}$ be the roots of the equation\n\n$$\np^{2} x^{2}+p^{3} x+1=0\n$$\n\nDetermine $p$ such that the expression $x_{1}^{4}+x_{2}^{4}$ has the smallest value.", "role": "user"}], "answer": "\\pm \\sqrt{2"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n663. The grasshopper jumped from the point with coordinate 8 to the point with coordinate 17.5. Then it made another jump of the same length (in the same direction). At the point with what coordinate did it end up?", "role": "user"}], "answer": "27"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n## Task 1 - 251211\n\nDetermine all pairs $(x ; y)$ of real numbers that satisfy the following system of equations (1), (2).\n\n$$\n\\begin{aligned}\n& x^{2}+y=1 \\\\\n& x+y^{2}=1\n\\end{aligned}\n$$", "role": "user"}], "answer": "\\left( \\frac{-1 - \\sqrt{5"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nThe radius of the Earth measures approximately $6378 \\mathrm{~km}$ at the Equator. Suppose a wire is exactly adjusted over the Equator.\n\nThen, suppose the length of the wire is increased by $1 \\mathrm{~m}$, so that the wire and the Equator form concentric circles around the Earth. Would a man standing, an ant, or an elephant be able to pass under this wire?", "role": "user"}], "answer": "An ant"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n10) In a bag there are some marbles. Maria says: \"In the bag there are three marbles in total and they are black.\" Luca says: \"In the bag there are two black marbles and two red marbles.\" Giorgio says: \"In the bag there are only black marbles.\" Knowing that only one of the three is lying, how many marbles are in the bag?\n\n(A) one, (B) two, (C) three, (D) four, (E) it is not possible to determine the number based on the information given in the problem.", "role": "user"}], "answer": "C"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n9. Four cousins Alan, Bob, Carl and Dan are $3,8,12$ and 14 years old, although not necessarily in that order. Alan is younger than Carl. The sum of the ages of Alan and Dan is divisible by 5. The sum of the ages of Carl and Dan is divisible by 5. What is the sum of the ages of Alan and Bob?\nA 26\nB 22\nC 17\nD 15\nE 11", "role": "user"}], "answer": "C"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n4. In $\\triangle A B C$, $\\angle A=30^{\\circ}, \\angle B=105^{\\circ}$, a line $D E$ is drawn through a point $D$ on side $A C$, intersecting side $A B$ or side $B C$ at point $E$, such that $\\angle C D E=60^{\\circ}$, and $D E$ bisects the area of $\\triangle A B C$. Then $\\left(\\frac{C D}{A C}\\right)^{2}=$ $\\qquad$ -", "role": "user"}], "answer": "\\dfrac{\\sqrt{3"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n1. (1) Use the Factor Theorem to prove that $a-b, b-c, c-a$ are all factors of $a^{2}(b-c)+b^{2}(c-a)+c^{2}(a-b)$.\n(2) Using the conclusion from (1), factorize $a^{2}(b-c)+b^{2}(c-a)+c^{2}(a-b)$.\n(3) Factorize: $(x+y+z)^{3}-x^{3}-y^{3}-z^{3}$.", "role": "user"}], "answer": "3(x + y)(y + z)(z + x)"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n## Problem Statement\n\nFind the point of intersection of the line and the plane.\n\n$\\frac{x+1}{3}=\\frac{y-3}{-4}=\\frac{z+1}{5}$\n\n$x+2 y-5 z+20=0$", "role": "user"}], "answer": "(2, -1, 4)"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nThe repeating decimals $0.abab\\overline{ab}$ and $0.abcabc\\overline{abc}$ satisfy\n\\[0.abab\\overline{ab}+0.abcabc\\overline{abc}=\\frac{33}{37},\\]\nwhere $a,b$, and $c$ are (not necessarily distinct) digits. Find the three-digit number $abc$.", "role": "user"}], "answer": "447"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n2 Find all integer $x$ such that $\\left|4 x^{2}-12 x-27\\right|$ is a prime number.\n\nFind all integer $x$ such that $\\left|4 x^{2}-12 x-27\\right|$ is a prime number.", "role": "user"}], "answer": "5"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n10,11\n\nThe angle in the development of the lateral surface of a cone is $120^{\\circ}$. Find the angle at the vertex of the axial section of the cone.", "role": "user"}], "answer": "\\arccos \\left( \\dfrac{7"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nExample 6 Find the number of $n$-digit numbers formed by $1,2,3$, where each of 1, 2, and 3 must appear at least once in the $n$-digit number.", "role": "user"}], "answer": "3^n - 3 \\cdot 2^n + 3"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n15 . In a $3 \\times 3$ grid, fill in the numbers $1,2,3,4,5,6,7,8,9$ so that the sum of the numbers in any three squares in a row, column, or diagonal is equal.", "role": "user"}], "answer": "\\begin{array"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n\n4. How many 6-tuples $\\left(a_{1}, a_{2}, a_{3}, a_{4}, a_{5}, a_{6}\\right)$ are there such that each of $a_{1}, a_{2}, a_{3}, a_{4}, a_{5}, a_{6}$ is from the set $\\{1,2,3,4\\}$ and the six expressions\n\n$$\na_{j}^{2}-a_{j} a_{j+1}+a_{j+1}^{2}\n$$\n\nfor $j=1,2,3,4,5,6$ (where $a_{7}$ is to be taken as $a_{1}$ ) are all equal to one another?\n", "role": "user"}], "answer": "40"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n3. In a right trapezoid $A B C D$, $A D / / B C$, $B C \\perp C D$, $E$ is the midpoint of side $A B$, $B C=C D=C E$. Then the degree measure of $\\angle B$ is ( ).\n(A) $52.5^{\\circ}$\n(B) $62.5^{\\circ}$\n(C) $60^{\\circ}$\n(D) $75^{\\circ}$", "role": "user"}], "answer": "D"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nProblem 4. The sum of eight consecutive natural numbers is equal to 92. What are these numbers?", "role": "user"}], "answer": "15"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nIn a tournament, any two players play against each other. Each player gets one point for a win, 1/2 for a draw, and 0 points for a loss. Let $S$ be the set of the 10 lowest scores. We know that each player obtained half of their score playing against players from $S$.\n\na) What is the sum of the scores of the players in $S$?\n\nb) Determine how many participants are in the tournament.\n\nNote: Each player plays only once against each opponent.", "role": "user"}], "answer": "25"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n9. (16 points) For a given positive integer $M$, define $f_{1}(M)$ as the square of the sum of the digits of $M$. When $n>1$ and $n \\in \\mathbf{N}$, $f_{n}\\left(f_{n-1}(M)\\right)$ represents the $r_{n}$-th power of the sum of the digits of $f_{n-1}(M)$, where, when $n$ is odd, $r_{n}=2$; when $n$ is even, $r_{n}=3$. Find the value of $f_{2012}\\left(f_{2011}\\left(3^{2010}\\right)\\right)$.", "role": "user"}], "answer": "should be \\( f_{2012}(f_{2011}(3^{2010})) \\)."} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nExample 4 Given $A(-2,2)$, and $B$ is a moving point on the ellipse $\\frac{x^{2}}{25}+\\frac{y^{2}}{16}=1$, $F$ is the left focus. When $\\mid A B \\mid +\\frac{5}{3}|B F|$ takes the minimum value, find the coordinates of point $B$.\n(1999, National High School Mathematics Competition)", "role": "user"}], "answer": "\\left( -\\dfrac{5\\sqrt{3"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n3. Given the sequence $\\left\\{a_{n}\\right\\}$ satisfies $a_{1}=\\frac{7}{6}$, and for any positive integer $n$, the quadratic equation $a_{n} x^{2}-$ $a_{n+1} x+1=0$ has two roots $\\alpha_{n}, \\beta_{n}$ that satisfy $6 \\alpha_{n}-2 \\alpha_{n} \\beta_{n}+6 \\beta_{n}=3$. Then the general term formula for $\\left\\{a_{n}\\right\\}$ is $a_{n}=$ $\\qquad$", "role": "user"}], "answer": "\\dfrac{2"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n4.1. Mom baked four raisin buns for breakfast for her two sons. $V$ In the first three buns, she put 7, 7, 23 raisins, and some more in the fourth. It turned out that the boys ate an equal number of raisins and did not divide any bun into parts. How many raisins could Mom have put in the fourth bun? List all the options.", "role": "user"}], "answer": "37"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nFind the number of ways in which three numbers can be selected from the set $\\{1,2,\\cdots ,4n\\}$, such that the sum of the three selected numbers is divisible by $4$.", "role": "user"}], "answer": "\\dfrac{n(4n -1)(2n -1)"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nAs shown in Figure $3, \\odot O$ is inside the rectangle $ABCD$. Tangents are drawn from vertices $A, B, C, D$ to $\\odot O$, with points of tangency being $A_{1}, B_{1}, C_{1}, D_{1}$, respectively. If $AA_{1}=3, BB_{1}=4$, $CC_{1}=5$, find the length of $DD_{1}$.", "role": "user"}], "answer": "3\\sqrt{2"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nCondition of the problem\n\nCalculate the limit of the function:\n\n$\\lim _{x \\rightarrow 1}\\left(\\frac{x^{3}-1}{x-1}\\right)^{\\frac{1}{x^{2}}}$", "role": "user"}], "answer": "3"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n$$\n\\begin{array}{l}\n\\text { Three. (20 points) (1) The quadratic function } \\\\\nf(x)=a x^{2}+b x+c(a, b, c \\in \\mathbf{R}, a \\neq 0)\n\\end{array}\n$$\n\nsatisfies\n(i) For $x \\in \\mathbf{R}$, there is $4 x \\leqslant f(x) \\leqslant \\frac{1}{2}(x+2)^{2}$\n\nalways holds;\n(ii) $f(-4+2 \\sqrt{3})=0$.\nFind $f(x)$.\n(2) Let $f_{1}(x)=\\frac{3}{2+x}, f_{n+1}(x)=f_{1}\\left(f_{n}(x)\\right)$, find $f_{2009}(0)$.", "role": "user"}], "answer": "\\dfrac{3^{2010"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n5. Let $S=\\left\\{(x, y) \\mid x^{2}-y^{2}=\\right.$ odd, $\\left.x, y \\in R\\right\\}, T=\\{(x, y) \\mid$ $\\left.\\sin \\left(2 \\pi x^{2}\\right)-\\sin \\left(2 \\pi y^{2}\\right)=\\cos \\left(2 \\pi x^{2}\\right)-\\cos \\left(2 \\pi y^{2}\\right), x, y \\in R\\right\\}$. Then\n(A) $S \\subset T$;\n(B) $T \\subset S$;\n(C) $S=T$;\n(D) $S \\cap T=\\Phi$.", "role": "user"}], "answer": "A"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n5. In trapezoid $A B C D$, $A B / / C D$, the base angles $\\angle D A B=36^{\\circ}, \\angle C B A=54^{\\circ}, M$ and $N$ are the midpoints of sides $A B$ and $C D$, respectively. If the lower base $A B$ is exactly 2008 units longer than the upper base $C D$, then the line segment $M N=$ $\\qquad$", "role": "user"}], "answer": "1004"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nThe seventh grades of our school competed in collecting caps from PET bottles. Class A collected half of what classes B and C collected together, class B collected a third of what classes A and C collected together, and class C collected 150 caps.\n\nDetermine how many caps these three classes collected in total.\n\n(M. Volfová)", "role": "user"}], "answer": "360"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nIn a certain year the price of gasoline rose by $20\\%$ during January, fell by $20\\%$ during February, rose by $25\\%$ during March, and fell by $x\\%$ during April. The price of gasoline at the end of April was the same as it had been at the beginning of January. To the nearest integer, what is $x$\n$\\mathrm{(A)}\\ 12\\qquad \\mathrm{(B)}\\ 17\\qquad \\mathrm{(C)}\\ 20\\qquad \\mathrm{(D)}\\ 25\\qquad \\mathrm{(E)}\\ 35$", "role": "user"}], "answer": "B"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n15. Given $f(x)=x^{2}+c$, and $f(f(x))=f\\left(x^{2}+1\\right)$.\n(1) Let $g(x)=f(f(x))$, find the analytical expression of the function $g(x)$;\n(2) Let $\\varphi(x)=g(x)-\\lambda f(x)$, try to find the value of the real number $\\lambda$ such that $\\varphi(x)$ is a decreasing function on $(-\\infty,-1]$ and an increasing function on $[-1,0)$.", "role": "user"}], "answer": "4"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nThe number $6545$ can be written as a product of a pair of positive two-digit numbers. What is the sum of this pair of numbers?\n$\\text{(A)}\\ 162 \\qquad \\text{(B)}\\ 172 \\qquad \\text{(C)}\\ 173 \\qquad \\text{(D)}\\ 174 \\qquad \\text{(E)}\\ 222$", "role": "user"}], "answer": "A"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n3. Given are the sides $a = BC$ and $b = CA$ of triangle $ABC$. Determine the length of the third side if it is equal to the length of the corresponding height. For which values of $a$ and $b$ does the problem have a solution?", "role": "user"}], "answer": "\\sqrt{\\dfrac{a^2 + b^2 + 2\\sqrt{3a^2b^2 - a^4 - b^4"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n## Task 15/85\n\nLet the numbers $a ; b ; c$ represent the side lengths of a triangle with perimeter $U$, and let $a^{2}$; $b^{2} ; c^{2}$ represent the side lengths of another triangle with perimeter $U^{\\prime}$. Determine the lower bound of the ratio $U^{2}: U^{\\prime}$!", "role": "user"}], "answer": "2"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n7. Let the edge length of a regular tetrahedron be $2 \\sqrt{6}$, and let a sphere be constructed with the center $O$ of the tetrahedron as its center. The total length of the curves formed by the intersection of the sphere's surface with the four faces of the tetrahedron is $4 \\pi$. Then the radius of the sphere $O$ is $\\qquad$", "role": "user"}], "answer": "\\dfrac{\\sqrt{5"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nExample 2.65. Calculate the volume of the body formed by the rotation around the $O Y$ axis of the curvilinear trapezoid bounded by the hyperbola $x y=2$ and the lines $y_{1}=1, y_{2}=4$ and $y_{3}=0$.", "role": "user"}], "answer": "3\\pi"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nFor two quadratic trinomials $P(x)$ and $Q(x)$ there is a linear function $\\ell(x)$ such that $P(x)=Q(\\ell(x))$ for all real $x$. How many such linear functions $\\ell(x)$ can exist?\n\n[i](A. Golovanov)[/i]", "role": "user"}], "answer": "2"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n1. A car is driving at a constant speed in one direction along a straight road, near which there are two houses. At noon, when the car had not yet reached the houses, the sum of the distances from it to these houses was 10 km. After 10 minutes, when the car had already passed both houses, it turned out that the sum of the distances from it to the houses was again 10 km. What is the speed of the car? (Problem author - I. Rubanov)", "role": "user"}], "answer": "60"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n$18 \\cdot 110$ As shown, $A B C D$ is an isosceles trapezoid, $A D$ $=B C=5, A B=4, D C=10$, point $C$ is on $D F$, and $B$ is the midpoint of the hypotenuse of the right triangle $\\triangle D E F$. Then $C F$ equals\n(A) 3.25 .\n(B) 3.5 .\n(C) 3.75 .\n(D) 4.0 .\n(E) 4.25 .", "role": "user"}], "answer": "D"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n1. Given 2117 cards, on which natural numbers from 1 to 2117 are written (each card has exactly one number, and the numbers do not repeat). It is required to choose two cards such that the sum of the numbers written on them is divisible by 100. In how many ways can this be done?", "role": "user"}], "answer": "22386"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n2. (6 points) A certain duplicator can print 3600 sheets of paper per hour, so printing 240 sheets of paper requires $\\qquad$ minutes.", "role": "user"}], "answer": "4"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n1 $\\left[\\begin{array}{ll}\\text { Common fractions }\\end{array}\\right]$\n\nWhich of the three fractions is the largest: $3 / 4, 4 / 5$ or $5 / 6$?", "role": "user"}], "answer": "\\dfrac{5"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nIn the given operation, the letters $a, b$, and $c$ represent distinct digits and are different from 1. Determine the values of $a, b$, and $c$.\n\n$$\n\\begin{array}{r}\na b b \\\\\n\\times \\quad c \\\\\n\\hline b c b 1\n\\end{array}\n$$", "role": "user"}], "answer": "c=7"} \ No newline at end of file diff --git a/samples/cli/finetuning/reinforcement/data/rft_validation_set.jsonl b/samples/cli/finetuning/reinforcement/data/rft_validation_set.jsonl new file mode 100644 index 000000000..133077906 --- /dev/null +++ b/samples/cli/finetuning/reinforcement/data/rft_validation_set.jsonl @@ -0,0 +1,10 @@ +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nExample 3 Given $a=\\frac{1}{2} \\sqrt{\\sqrt{2}+\\frac{1}{8}}-\\frac{\\sqrt{2}}{8}$. Try to find the value of $a^{2}+\\sqrt{a^{4}+a+1}$.", "role": "user"}], "answer": "\\sqrt{2"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nThe surface area of a cube is 24 . The volume of the cube is\n(A) 4\n(B) $3 \\sqrt{3}$\n(C) 9\n(D) 16\n(E) 8", "role": "user"}], "answer": "E"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n2. Given $\\sin 2 x=\\frac{\\sin \\theta+\\cos \\theta}{2}$, $\\cos ^{2} x=\\sin \\theta \\cdot \\cos \\theta$.\nThen, the value of $\\cos 2 x$ is ( ).\n(A) $\\frac{-1 \\pm \\sqrt{33}}{8}$\n(B) $\\frac{-1+\\sqrt{33}}{8}$\n(C) $\\frac{-1-\\sqrt{33}}{8}$\n(D) 0", "role": "user"}], "answer": "C"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n4. Find the sum\n\n$$\n\\log \\operatorname{tg} 1^{\\circ}+\\log \\operatorname{tg} 2^{\\circ}+\\ldots+\\log \\operatorname{tg} 89^{\\circ}\n$$", "role": "user"}], "answer": "0"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n1. Find the sum of the numbers:\n\n$$\n3+33+333+3333+\\cdots+\\underbrace{33333 \\ldots 3}_{2018 \\text { of them }} .\n$$", "role": "user"}], "answer": "\\dfrac{10^{2019"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\n12.407 A line perpendicular to the chord of a segment divides the chord in the ratio 1:4, and the arc - in the ratio $1: 2$. Find the cosine of the central angle subtended by this arc.", "role": "user"}], "answer": "-\\dfrac{23"} +{"messages": [{"content": "You are a mathematical reasoning expert. Solve problems with detailed step-by-step thinking and provide final answers in \\boxed{} format. Show all intermediate calculations and explain your reasoning clearly.\n\nFor some positive integer $n$, a coin will be flipped $n$ times to obtain a sequence of $n$ heads and tails. For each flip of the coin, there is probability $p$ of obtaining a head and probability $1-p$ of obtaining a tail, where $0 - - + + + + + + + + diff --git a/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/Program.cs b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/Program.cs index 3a2ae0867..053c53497 100644 --- a/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/Program.cs +++ b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/Program.cs @@ -1,321 +1,194 @@ -// ------------------------------------ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -// ------------------------------------ - -// +// +using Azure; +using Azure.AI.Projects; +using Azure.AI.Projects.OpenAI; +using Azure.Core; +using Azure.Identity; +using DotNetEnv; +using OpenAI.Responses; using System; -using System.ClientModel; using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.IO.Enumeration; +using System.Runtime.CompilerServices; using System.Text.Json; -using System.Threading; -using Azure.AI.Projects; -using Azure.Identity; +using System.Threading.Tasks; // - -namespace Evaluate; - -public class Program +#pragma warning disable OPENAI001 +class EvaluateProgram { - public static void Main(string[] args) + private static string GetFile(string name, [CallerFilePath] string pth = "") { - // - // Load environment variables - var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT") - ?? throw new InvalidOperationException("PROJECT_ENDPOINT not set"); - var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") - ?? "gpt-4o-mini"; - - // Create clients - AIProjectClient projectClient = new(new Uri(endpoint), new DefaultAzureCredential()); - EvaluationClient evaluationClient = projectClient.OpenAI.GetEvaluationClient(); + var dirName = Path.GetDirectoryName(pth) ?? ""; + return Path.Combine(dirName, "..", "shared", name); + } - // Create or retrieve the agent to evaluate - PromptAgentDefinition agentDefinition = new(model: modelDeploymentName) + static async Task Main(string[] args) + { + // Load environment variables from shared directory + Env.Load(GetFile(".env")); + + var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT"); + var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME"); + var sharepointConnectionId = Environment.GetEnvironmentVariable("SHAREPOINT_CONNECTION_ID"); + var mcpServerUrl = Environment.GetEnvironmentVariable("MCP_SERVER_URL"); + var tenantId = Environment.GetEnvironmentVariable("AI_FOUNDRY_TENANT_ID"); + + // Use tenant-specific credential if provided + TokenCredential credential; + if (!string.IsNullOrEmpty(tenantId)) { - Instructions = "You are a helpful Modern Workplace Assistant that answers questions about company policies and technical guidance." - }; - AgentVersion agentVersion = projectClient.Agents.CreateAgentVersion( - agentName: "Modern Workplace Assistant", - options: new(agentDefinition)); - Console.WriteLine($"Agent created (id: {agentVersion.Id}, name: {agentVersion.Name}, version: {agentVersion.Version})"); + credential = new AzureCliCredential(new AzureCliCredentialOptions { TenantId = tenantId }); + } + else + { + credential = new DefaultAzureCredential(); + } - // Define testing criteria with built-in evaluators - // data_mapping: sample.output_text = agent string response, sample.output_items = structured JSON with tool calls - object[] testingCriteria = [ - new { - type = "azure_ai_evaluator", - name = "violence_detection", - evaluator_name = "builtin.violence", - data_mapping = new { query = "{{item.query}}", response = "{{sample.output_text}}" } - }, - new { - type = "azure_ai_evaluator", - name = "fluency", - evaluator_name = "builtin.fluency", - initialization_parameters = new { deployment_name = modelDeploymentName }, - data_mapping = new { query = "{{item.query}}", response = "{{sample.output_text}}" } - }, - new { - type = "azure_ai_evaluator", - name = "task_adherence", - evaluator_name = "builtin.task_adherence", - initialization_parameters = new { deployment_name = modelDeploymentName }, - data_mapping = new { query = "{{item.query}}", response = "{{sample.output_items}}" } - }, - ]; + AIProjectClient client = new(new Uri(projectEndpoint), credential); - // Define the data schema - object dataSourceConfig = new - { - type = "custom", - item_schema = new - { - type = "object", - properties = new { query = new { type = "string" } }, - required = new[] { "query" } - }, - include_sample_schema = true - }; + Console.WriteLine("🧪 Modern Workplace Assistant Evaluation\n"); - // Create evaluation data payload - BinaryData evaluationData = BinaryData.FromObjectAsJson(new + var instructions = @"You are a Modern Workplace Assistant for Contoso Corporation. +Answer questions using available tools and provide specific, detailed responses."; + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(modelDeploymentName) { - name = "Agent Evaluation", - data_source_config = dataSourceConfig, - testing_criteria = testingCriteria - }); - - // Create the evaluation object - using BinaryContent evaluationDataContent = BinaryContent.Create(evaluationData); - ClientResult evaluation = evaluationClient.CreateEvaluation(evaluationDataContent); - Dictionary fields = ParseClientResult(evaluation, ["name", "id"]); - string evaluationName = fields["name"]; - string evaluationId = fields["id"]; - Console.WriteLine($"Evaluation created (id: {evaluationId}, name: {evaluationName})"); - // + Instructions = instructions + }; - // - // Define the data source for the evaluation run - // This targets the agent with test queries - object dataSource = new + // Add SharePoint tool if configured + if (!string.IsNullOrEmpty(sharepointConnectionId)) { - type = "azure_ai_target_completions", - source = new - { - type = "file_content", - content = new[] - { - new { item = new { query = "What is Contoso's remote work policy?" } }, - new { item = new { query = "What are the security requirements for remote employees?" } }, - new { item = new { query = "According to Microsoft Learn, how do I configure Azure AD Conditional Access?" } }, - new { item = new { query = "Based on our company policy, how should I configure Azure security to comply?" } }, - } - }, - input_messages = new + try { - type = "template", - template = new[] + SharePointGroundingToolOptions sharepointToolOption = new() { - new - { - type = "message", - role = "user", - content = new { type = "input_text", text = "{{item.query}}" } - } - } - }, - target = new + ProjectConnections = { new ToolProjectConnection(projectConnectionId: sharepointConnectionId) } + }; + SharepointPreviewTool sharepointTool = new(sharepointToolOption); + agentDefinition.Tools.Add(sharepointTool); + Console.WriteLine("✅ SharePoint configured for evaluation"); + } + catch (Exception ex) { - type = "azure_ai_agent", - name = agentVersion.Name, - // Version is optional. Defaults to latest version if not specified. - version = agentVersion.Version, + Console.WriteLine($"⚠️ SharePoint unavailable: {ex.Message}"); } - }; - - // Create evaluation run payload - BinaryData runData = BinaryData.FromObjectAsJson(new - { - eval_id = evaluationId, - name = $"Evaluation Run for Agent {agentVersion.Name}", - data_source = dataSource - }); - - // Submit the evaluation run - using BinaryContent runDataContent = BinaryContent.Create(runData); - ClientResult run = evaluationClient.CreateEvaluationRun(evaluationId: evaluationId, content: runDataContent); - fields = ParseClientResult(run, ["id", "status"]); - string runId = fields["id"]; - string runStatus = fields["status"]; - Console.WriteLine($"Evaluation run created (id: {runId})"); - // - - // - // Poll until the evaluation run completes - while (runStatus != "failed" && runStatus != "completed") - { - Thread.Sleep(TimeSpan.FromMilliseconds(5000)); - run = evaluationClient.GetEvaluationRun(evaluationId: evaluationId, evaluationRunId: runId, options: new()); - runStatus = ParseClientResult(run, ["status"])["status"]; - Console.WriteLine($"Waiting for eval run to complete... current status: {runStatus}"); } - if (runStatus == "failed") + // Add MCP tool if configured + if (!string.IsNullOrEmpty(mcpServerUrl)) { - throw new InvalidOperationException($"Evaluation run failed with error: {GetErrorMessageOrEmpty(run)}"); + try + { + McpTool mcpTool = ResponseTool.CreateMcpTool( + serverLabel: "microsoft_learn", + serverUri: new Uri(mcpServerUrl), + toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval) + ); + agentDefinition.Tools.Add(mcpTool); + Console.WriteLine("✅ MCP configured for evaluation"); + } + catch (Exception ex) + { + Console.WriteLine($"⚠️ MCP unavailable: {ex.Message}"); + } } - // Output results - Console.WriteLine("\n✓ Evaluation run completed successfully!"); - Console.WriteLine($"Result Counts: {GetResultsCounts(run)}"); - - List evaluationResults = GetResultsList( - client: evaluationClient, - evaluationId: evaluationId, - evaluationRunId: runId); + Console.WriteLine(); - Console.WriteLine($"\nOUTPUT ITEMS (Total: {evaluationResults.Count})"); - Console.WriteLine($"{new string('-', 60)}"); - foreach (string result in evaluationResults) - { - Console.WriteLine(result); - } - Console.WriteLine($"{new string('-', 60)}"); + AgentVersion agent = await client.Agents.CreateAgentVersionAsync( + agentName: "EvaluationAgent", + options: new(agentDefinition) + ); - // Cleanup - evaluationClient.DeleteEvaluation(evaluationId, new System.ClientModel.Primitives.RequestOptions()); - Console.WriteLine("Evaluation deleted"); + // + var questions = File.ReadAllLines(GetFile("questions.jsonl")) + .Select(line => JsonSerializer.Deserialize(line)) + .ToList(); + // - projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version); - Console.WriteLine("Agent deleted"); - // - } + // + // NOTE: This code is a non-runnable snippet of the larger sample code from which it is taken. + var results = new List(); - // - /// - /// Parses string values from top-level JSON properties in a ClientResult. - /// - private static Dictionary ParseClientResult(ClientResult result, string[] expectedProperties) - { - Dictionary results = new(); - Utf8JsonReader reader = new(result.GetRawResponse().Content.ToMemory().ToArray()); - JsonDocument document = JsonDocument.ParseValue(ref reader); + Console.WriteLine($"Running {questions.Count} evaluation questions...\n"); - foreach (JsonProperty prop in document.RootElement.EnumerateObject()) + for (int i = 0; i < questions.Count; i++) { - foreach (string key in expectedProperties) + var q = questions[i]; + var question = q.GetProperty("question").GetString()!; + + string[] expectedKeywords = Array.Empty(); + if (q.TryGetProperty("expected_keywords", out var keywordsElem)) { - if (prop.NameEquals(Encoding.UTF8.GetBytes(key)) && prop.Value.ValueKind == JsonValueKind.String) - { - results[key] = prop.Value.GetString()!; - } + expectedKeywords = keywordsElem.EnumerateArray() + .Select(e => e.GetString()!) + .ToArray(); } - } - List notFoundItems = expectedProperties.Where(key => !results.ContainsKey(key)).ToList(); - if (notFoundItems.Count > 0) - { - throw new InvalidOperationException($"Keys not found in result: {string.Join(", ", notFoundItems)}"); - } - return results; - } + Console.WriteLine($"Question {i + 1}/{questions.Count}: {question}"); - /// - /// Gets error message from a ClientResult if present. - /// - private static string GetErrorMessageOrEmpty(ClientResult result) - { - Utf8JsonReader reader = new(result.GetRawResponse().Content.ToMemory().ToArray()); - JsonDocument document = JsonDocument.ParseValue(ref reader); - string? code = null; - string? message = null; + // Create a conversation to maintain state + ProjectConversation conversation = await client.OpenAI.Conversations.CreateProjectConversationAsync(); - foreach (JsonProperty prop in document.RootElement.EnumerateObject()) - { - if (prop.NameEquals("error"u8) && prop.Value.ValueKind != JsonValueKind.Null) + // Get OpenAI client from the agents client + ProjectResponsesClient responseClient = client.OpenAI.GetProjectResponsesClientForAgent(agent, conversation.Id); + + // Create the user message item + List items = [ResponseItem.CreateUserMessageItem(question)]; + + string response = ""; + try { - foreach (JsonProperty errorNode in prop.Value.EnumerateObject()) - { - if (errorNode.Value.ValueKind == JsonValueKind.String) - { - if (errorNode.NameEquals("code"u8)) code = errorNode.Value.GetString(); - else if (errorNode.NameEquals("message"u8)) message = errorNode.Value.GetString(); - } - } + // Create response from the agent + ResponseResult openAIResponse = await responseClient.CreateResponseAsync(items); + response = openAIResponse.GetOutputText(); + } + catch (Exception ex) + { + Console.WriteLine($" ⚠️ Error: {ex.Message}"); + response = ""; } - } - return string.IsNullOrEmpty(message) ? "" : $"Message: {message}, Code: {code ?? ""}"; - } - - /// - /// Formats the result_counts property from a ClientResult. - /// - private static string GetResultsCounts(ClientResult result) - { - Utf8JsonReader reader = new(result.GetRawResponse().Content.ToMemory().ToArray()); - JsonDocument document = JsonDocument.ParseValue(ref reader); - StringBuilder sb = new("{\n"); - foreach (JsonProperty prop in document.RootElement.EnumerateObject()) - { - if (prop.NameEquals("result_counts"u8) && prop.Value is JsonElement countsElement) + bool passed = response.Length > 50; + if (expectedKeywords.Length > 0) { - foreach (JsonProperty count in countsElement.EnumerateObject()) - { - if (count.Value.ValueKind == JsonValueKind.Number) - { - sb.Append($" {count.Name}: {count.Value.GetInt32()}\n"); - } - } + passed = passed && expectedKeywords.Any(k => response.Contains(k, StringComparison.OrdinalIgnoreCase)); } + + Console.WriteLine($" Status: {(passed ? "✅ PASS" : "❌ FAIL")}"); + Console.WriteLine($" Response length: {response.Length} characters\n"); + + results.Add(new + { + question, + response, + passed, + response_length = response.Length + }); } - sb.Append('}'); - return sb.ToString(); - } + // - /// - /// Retrieves all output items from an evaluation run (handles pagination). - /// - private static List GetResultsList(EvaluationClient client, string evaluationId, string evaluationRunId) - { - List resultJsons = new(); - bool hasMore; + // Cleanup - Note: In SDK 2.0, agents are versioned and managed differently + // await client.DeleteAgentAsync(agent.Name); // Uncomment if you want to delete - do + // + // NOTE: This code is a non-runnable snippet of the larger sample code from which it is taken. + var summary = new { - ClientResult resultList = client.GetEvaluationRunOutputItems( - evaluationId: evaluationId, - evaluationRunId: evaluationRunId, - limit: null, - order: "asc", - after: default, - outputItemStatus: default, - options: new()); - - Utf8JsonReader reader = new(resultList.GetRawResponse().Content.ToMemory().ToArray()); - JsonDocument document = JsonDocument.ParseValue(ref reader); - hasMore = false; + total_questions = questions.Count, + passed = results.Count(r => ((dynamic)r).passed), + failed = results.Count(r => !((dynamic)r).passed), + results + }; - foreach (JsonProperty topProperty in document.RootElement.EnumerateObject()) - { - if (topProperty.NameEquals("has_more"u8)) - { - hasMore = topProperty.Value.GetBoolean(); - } - else if (topProperty.NameEquals("data"u8) && topProperty.Value.ValueKind == JsonValueKind.Array) - { - foreach (JsonElement dataElement in topProperty.Value.EnumerateArray()) - { - resultJsons.Add(dataElement.ToString()); - } - } - } - } while (hasMore); + var json = JsonSerializer.Serialize(summary, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText("evaluation_results.json", json); - return resultJsons; + Console.WriteLine($"📊 Evaluation Complete:"); + Console.WriteLine($" Total: {summary.total_questions}"); + Console.WriteLine($" Passed: {summary.passed}"); + Console.WriteLine($" Failed: {summary.failed}"); + Console.WriteLine($"\n📄 Results saved to evaluation_results.json"); + // } - // } diff --git a/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/nuget.config b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/nuget.config index 7f3fb6f6f..abbb7d618 100644 --- a/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/nuget.config +++ b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/Evaluate/nuget.config @@ -2,7 +2,6 @@ - - + diff --git a/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/ModernWorkplaceAssistant/nuget.config b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/ModernWorkplaceAssistant/nuget.config index 7f3fb6f6f..abbb7d618 100644 --- a/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/ModernWorkplaceAssistant/nuget.config +++ b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/ModernWorkplaceAssistant/nuget.config @@ -2,7 +2,6 @@ - - + diff --git a/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/shared/questions.jsonl b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/shared/questions.jsonl new file mode 100644 index 000000000..dc4a62499 --- /dev/null +++ b/samples/csharp/enterprise-agent-tutorial/1-idea-to-prototype/shared/questions.jsonl @@ -0,0 +1,2 @@ +{"question": "Please explain, what is MCP Server."} +{"question": "Define the Maxwell's equation."} diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/AgentThreadAndHITL.csproj b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/AgentThreadAndHITL.csproj new file mode 100644 index 000000000..dce28b582 --- /dev/null +++ b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/AgentThreadAndHITL.csproj @@ -0,0 +1,21 @@ + + + + Exe + net9.0 + enable + enable + + + + $(NoWarn);MEAI001 + + + + + + + + + + diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Dockerfile b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Dockerfile new file mode 100644 index 000000000..0d3e5757c --- /dev/null +++ b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Dockerfile @@ -0,0 +1,20 @@ +# Build the application +FROM mcr.microsoft.com/dotnet/sdk:9.0-alpine AS build +WORKDIR /src + +# Copy files from the current directory on the host to the working directory in the container +COPY . . + +RUN dotnet restore +RUN dotnet build -c Release --no-restore +RUN dotnet publish -c Release --no-build -o /app + +# Run the application +FROM mcr.microsoft.com/dotnet/aspnet:9.0-alpine AS final +WORKDIR /app + +# Copy everything needed to run the app from the "build" stage. +COPY --from=build /app . + +EXPOSE 8088 +ENTRYPOINT ["dotnet", "AgentsInWorkflows.dll"] diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Program.cs b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Program.cs new file mode 100644 index 000000000..43a4c2967 --- /dev/null +++ b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/Program.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft. All rights reserved. + +using System.ComponentModel; +using Azure.AI.AgentServer.AgentFramework.Extensions; +using Azure.AI.AgentServer.AgentFramework.Persistence; +using Azure.AI.OpenAI; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using OpenAI; + +namespace AgengThreadAndHITL; + +public partial class Program +{ + public static async Task Main() + { + var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set."); + var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + + // Create a sample function tool that the agent can use. + [Description("Get the weather for a given location.")] + static string GetWeather([Description("The location to get the weather for.")] string location) + => $"The weather in {location} is cloudy with a high of 15°C."; + + // Create the chat client and agent. + // Note that we are wrapping the function tool with ApprovalRequiredAIFunction to require user approval before invoking it. + // user should reply with 'approve' or 'reject' when prompted. + + AIAgent agent = new AzureOpenAIClient( + new Uri(endpoint), + new AzureCliCredential()) + .GetChatClient(deploymentName) + .CreateAIAgent( + instructions: "You are a helpful assistant", + tools: [new ApprovalRequiredAIFunction(AIFunctionFactory.Create(GetWeather))] + ); + + var threadRespository = new InMemoryAgentThreadRepository(agent); + await agent.RunAIAgentAsync(telemetrySourceName: "Agents", threadRepository: threadRespository); + } +} diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/README.md b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/README.md new file mode 100644 index 000000000..6011f0ddf --- /dev/null +++ b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/README.md @@ -0,0 +1,104 @@ +**IMPORTANT!** All samples and other resources made available in this GitHub repository ("samples") are designed to assist in accelerating development of agents, solutions, and agent workflows for various scenarios. Review all provided resources and carefully test output behavior in the context of your use case. AI responses may be inaccurate and AI actions should be monitored with human oversight. Learn more in the transparency documents for [Agent Service](https://learn.microsoft.com/en-us/azure/ai-foundry/responsible-ai/agents/transparency-note) and [Agent Framework](https://github.com/microsoft/agent-framework/blob/main/TRANSPARENCY_FAQ.md). + +Agents, solutions, or other output you create may be subject to legal and regulatory requirements, may require licenses, or may not be suitable for all industries, scenarios, or use cases. By using any sample, you are acknowledging that any output created using those samples are solely your responsibility, and that you will comply with all applicable laws, regulations, and relevant safety standards, terms of service, and codes of conduct. + +Third-party samples contained in this folder are subject to their own designated terms, and they have not been tested or verified by Microsoft or its affiliates. + +Microsoft has no responsibility to you or others with respect to any of these samples or any resulting output. + +# What this sample demonstrates + +This sample demonstrates how to use AI agents as executors within a workflow, hosted using +[Azure AI AgentServer SDK](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/ai.agentserver.agentframework-readme) and +deploy it to Microsoft Foundry using the Azure Developer CLI [ai agent](https://aka.ms/azdaiagent/docs) extension. + +## How It Works + +### Weather Assistant Agent + +This sample demonstrates the integration of AI agents with a function tool involving human approval. + +The agents are connected sequentially in a workflow, creating a translation chain that demonstrates: + +- How AgentServer adapter use a ThreadRepository to manage conversation history. +- The AgentServer adapter converts human approval request to a FunctionCall with function name `__hosted_agent_adapter_hitl__` +- User approve or deny the request by responding `approved` or `denied` as a FunctionCallOutput. + +### Agent Hosting + +The agent workflow is hosted using the [Azure AI AgentServer SDK](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/ai.agentserver.agentframework-readme), +which provisions a REST API endpoint compatible with the OpenAI Responses protocol. This allows interaction with the agent workflow using OpenAI Responses compatible clients. + +### Agent Deployment + +The hosted agent workflow can be seamlessly deployed to Microsoft Foundry using the Azure Developer CLI [ai agent](https://aka.ms/azdaiagent/docs) extension. +The extension builds a container image for the agent, deploys it to Azure Container Instances (ACI), and creates a hosted agent version and deployment on Foundry Agent Service. + +## Running the Agent Locally + +### Prerequisites + +Before running this sample, ensure you have: + +1. An Azure OpenAI endpoint configured +2. A deployment of a chat model (e.g., `gpt-4o-mini`) +3. Azure CLI installed and authenticated (`az login`) +4. .NET 9.0 SDK or later installed + +### Environment Variables + +Set the following environment variables: + +- `AZURE_OPENAI_ENDPOINT` - Your Azure OpenAI endpoint URL (required) +- `AZURE_OPENAI_DEPLOYMENT_NAME` - The deployment name for your chat model (optional, defaults to `gpt-4o-mini`) + +**PowerShell:** + +```powershell +# Replace with your Azure OpenAI endpoint +$env:AZURE_OPENAI_ENDPOINT="https://your-openai-resource.openai.azure.com/" + +# Optional, defaults to gpt-4o-mini +$env:AZURE_OPENAI_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +### Running the Sample + +To run the agent, execute the following command in your terminal: + +```powershell +dotnet run +``` + +This will start the hosted agent workflow locally on `http://localhost:8080/`. + +### Interacting with the Agent + +You can interact with the agent workflow using: + +- The `test_requests.py` file in this directory to test and prompt the agent +- Any OpenAI Responses compatible client by sending requests to `http://localhost:8080/` + +Try providing text to ask the weather assistant agent about the weather in a city. + +### Deploying the Agent to Microsoft Foundry + +To deploy your agent to Microsoft Foundry, follow the comprehensive deployment guide at https://aka.ms/azdaiagent/docs + +## Troubleshooting + +### Images built on Apple Silicon or other ARM64 machines do not work on our service + +We **recommend using `azd` cloud build**, which always builds images with the correct architecture. + +If you choose to **build locally**, and your machine is **not `linux/amd64`** (for example, an Apple Silicon Mac), the image will **not be compatible with our service**, causing runtime failures. + +**Fix for local builds** + +Add this line at the top of your `Dockerfile`: + +```dockerfile +FROM --platform=linux/amd64 python:3.12-slim +``` + +This forces the image to be built for the required `amd64` architecture. diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/agent.yaml b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/agent.yaml new file mode 100644 index 000000000..cbd0cde1b --- /dev/null +++ b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/agent.yaml @@ -0,0 +1,29 @@ +name: AgentThreadAndHITL +displayName: "Weather Assistant Agent" +description: > + A Weather Assistant Agent that provides weather information and forecasts. It + demonstrates how to use Azure AI AgentServer with Human-in-the-Loop (HITL) + capabilities to get human approval for funtional calls. + +metadata: + authors: + - Hosted Agent Team + tags: + - Azure AI AgentServer + - Microsoft Agent Framework + - Human-in-the-Loop +template: + kind: hosted + name: AgentThreadAndHITL + protocols: + - protocol: responses + version: v1 + environment_variables: + - name: AZURE_OPENAI_ENDPOINT + value: ${AZURE_OPENAI_ENDPOINT} + - name: AZURE_OPENAI_DEPLOYMENT_NAME + value: "{{chat}}" +resources: + - name: chat + kind: model + id: gpt-4o diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/test_requests.py b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/test_requests.py new file mode 100644 index 000000000..a28f54f04 --- /dev/null +++ b/samples/csharp/hosted-agents/AgentFramework/AgentThreadAndHITL/test_requests.py @@ -0,0 +1,67 @@ +import json +import requests + +url = "http://localhost:8088/responses" +stream = False + + +input = "What is the weather like in Vancouver?" +payload = { + "agent": {"name": "local_agent", "type": "agent_reference"}, + "tools": [], + "stream": stream, + "input": input, +} + +call_id = None +conversation_id = None + +try: + response = requests.post(url, json=payload) + + response.raise_for_status() # Raise an error for HTTP errors + response_detail = None + + print(json.dumps(response.json(), indent=2)) + response_detail = response.json() + + conversation_id = response_detail.get("conversation", {}).get("id") + output = response_detail.get("output", []) + for item in output: + if item.get("type") == "function_call" and item.get("name") == "__hosted_agent_adapter_hitl__": + call_id = item.get("call_id") + request_detail = json.loads(item.get("arguments", "{}")) +except Exception as e: + print(f"Error: {e}") + +print("\n\n") + +print(f"conversation_id: {conversation_id}") +print(f"call_id: {call_id}") + +if not conversation_id or not call_id: + print("Failed to parse hitl request info") +else: + human_feedback = { + "call_id": call_id, + "output": "approve", + "type": "function_call_output", + } + + feedback_payload = { + "agent": {"name": "local_agent", "type": "agent_reference"}, + "tools": [], + "stream": stream, + "input": [human_feedback], + "conversation": {"id": conversation_id} + } + + try: + print("\n\nsending feedback...") + print(json.dumps(feedback_payload, indent=2)) + response = requests.post(url, json=feedback_payload) + response.raise_for_status() # Raise an error for HTTP errors + print("\n\nagent response:") + print(json.dumps(response.json(), indent=2)) + except Exception as e: + print(f"Error: {e}") diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentWithHostedMCP/AgentWithHostedMCP.csproj b/samples/csharp/hosted-agents/AgentFramework/AgentWithHostedMCP/AgentWithHostedMCP.csproj index 2ec55d125..ba80d2c1b 100644 --- a/samples/csharp/hosted-agents/AgentFramework/AgentWithHostedMCP/AgentWithHostedMCP.csproj +++ b/samples/csharp/hosted-agents/AgentFramework/AgentWithHostedMCP/AgentWithHostedMCP.csproj @@ -11,7 +11,7 @@ - + diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentWithTextSearchRag/AgentWithTextSearchRag.csproj b/samples/csharp/hosted-agents/AgentFramework/AgentWithTextSearchRag/AgentWithTextSearchRag.csproj index d606cbb37..40c9a2544 100644 --- a/samples/csharp/hosted-agents/AgentFramework/AgentWithTextSearchRag/AgentWithTextSearchRag.csproj +++ b/samples/csharp/hosted-agents/AgentFramework/AgentWithTextSearchRag/AgentWithTextSearchRag.csproj @@ -9,7 +9,7 @@ - + diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentWithTools/AgentWithTools.csproj b/samples/csharp/hosted-agents/AgentFramework/AgentWithTools/AgentWithTools.csproj index 3b222e343..85c5105fd 100644 --- a/samples/csharp/hosted-agents/AgentFramework/AgentWithTools/AgentWithTools.csproj +++ b/samples/csharp/hosted-agents/AgentFramework/AgentWithTools/AgentWithTools.csproj @@ -8,7 +8,7 @@ - + diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/AgentsInWorkflows.csproj b/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/AgentsInWorkflows.csproj index 1ad14a7f0..a25b0b6b0 100644 --- a/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/AgentsInWorkflows.csproj +++ b/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/AgentsInWorkflows.csproj @@ -9,10 +9,10 @@ - + - + diff --git a/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/Program.cs b/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/Program.cs index b1d8a922f..279d1de21 100644 --- a/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/Program.cs +++ b/samples/csharp/hosted-agents/AgentFramework/AgentsInWorkflows/Program.cs @@ -4,6 +4,7 @@ // Three translation agents are connected sequentially to create a translation chain: // English → French → Spanish → English, showing how agents can be composed as workflow executors. +using Azure.AI.AgentServer.AgentFramework; using Azure.AI.AgentServer.AgentFramework.Extensions; using Azure.AI.OpenAI; using Azure.Identity; @@ -24,14 +25,18 @@ AIAgent spanishAgent = GetTranslationAgent("Spanish", chatClient); AIAgent englishAgent = GetTranslationAgent("English", chatClient); -// Build the workflow and turn it into an agent -AIAgent agent = new WorkflowBuilder(frenchAgent) - .AddEdge(frenchAgent, spanishAgent) - .AddEdge(spanishAgent, englishAgent) - .Build() - .AsAgent(); - -await agent.RunAIAgentAsync(); +WorkflowAgentFactory factory = () => +{ + // Build the workflow and turn it into an agent + AIAgent agent = new WorkflowBuilder(frenchAgent) + .AddEdge(frenchAgent, spanishAgent) + .AddEdge(spanishAgent, englishAgent) + .Build() + .AsAgent(); + return Task.FromResult(agent); +}; + +await factory.RunWorkflowAgentAsync(telemetrySourceName: "Agents"); static ChatClientAgent GetTranslationAgent(string targetLanguage, IChatClient chatClient) => new(chatClient, $"You are a translation assistant that translates the provided text to {targetLanguage}."); diff --git a/samples/csharp/hosted-agents/AgentWithCustomFramework/SystemUtilityAgent/SystemUtilityAgent.csproj b/samples/csharp/hosted-agents/AgentWithCustomFramework/SystemUtilityAgent/SystemUtilityAgent.csproj index 718964c35..4d8f573c6 100644 --- a/samples/csharp/hosted-agents/AgentWithCustomFramework/SystemUtilityAgent/SystemUtilityAgent.csproj +++ b/samples/csharp/hosted-agents/AgentWithCustomFramework/SystemUtilityAgent/SystemUtilityAgent.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/samples/csharp/quickstart/AgentService.cs b/samples/csharp/quickstart/AgentService.cs index 4bca72bd1..f3ba7dd0d 100644 --- a/samples/csharp/quickstart/AgentService.cs +++ b/samples/csharp/quickstart/AgentService.cs @@ -1,23 +1,21 @@ // This sample combines each step of creating and running agents and conversations into a single example. // In practice, you would typically separate these steps into different applications. // -using Azure.AI.Agents; +using Azure.AI.Projects; +using Azure.AI.Projects.OpenAI; using Azure.Identity; -using OpenAI; using OpenAI.Responses; #pragma warning disable OPENAI001 -string RAW_PROJECT_ENDPOINT = Environment.GetEnvironmentVariable("AZURE_AI_FOUNDRY_PROJECT_ENDPOINT") - ?? throw new InvalidOperationException("Missing environment variable 'AZURE_AI_FOUNDRY_PROJECT_ENDPOINT'"); -string MODEL_DEPLOYMENT = Environment.GetEnvironmentVariable("AZURE_AI_FOUNDRY_MODEL_DEPLOYMENT_NAME") - ?? throw new InvalidOperationException("Missing environment variable 'AZURE_AI_FOUNDRY_MODEL_DEPLOYMENT_NAME'"); -string AGENT_NAME = Environment.GetEnvironmentVariable("AZURE_AI_FOUNDRY_AGENT_NAME") - ?? throw new InvalidOperationException("Missing environment variable 'AZURE_AI_FOUNDRY_AGENT_NAME'"); +string RAW_PROJECT_ENDPOINT = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT") +?? throw new InvalidOperationException("Missing environment variable 'PROJECT_ENDPOINT'"); +string MODEL_DEPLOYMENT = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") +?? throw new InvalidOperationException("Missing environment variable 'MODEL_DEPLOYMENT_NAME'"); +string AGENT_NAME = Environment.GetEnvironmentVariable("AGENT_NAME") +?? throw new InvalidOperationException("Missing environment variable 'AGENT_NAME'"); -AgentClient agentsClient = new(new Uri(RAW_PROJECT_ENDPOINT), new AzureCliCredential()); -OpenAIClient openAIClient = agentsClient.GetOpenAIClient(); -OpenAIResponseClient responseClient = openAIClient.GetOpenAIResponseClient(MODEL_DEPLOYMENT); +AIProjectClient projectClient = new AIProjectClient(new Uri(RAW_PROJECT_ENDPOINT), new DefaultAzureCredential()); // // Create an agent version for a new prompt agent @@ -27,25 +25,25 @@ { Instructions = "You are a foo bar agent. In EVERY response you give, ALWAYS include both `foo` and `bar` strings somewhere in the response.", }; -AgentVersion newAgentVersion = await agentsClient.CreateAgentVersionAsync(AGENT_NAME, options: new(agentDefinition)); +AgentVersion newAgentVersion = await projectClient.Agents.CreateAgentVersionAsync(AGENT_NAME, options: new(agentDefinition)); // // Create a conversation to maintain state between calls // -AgentConversationCreationOptions conversationOptions = new() +ProjectConversationCreationOptions conversationOptions = new() { Items = { ResponseItem.CreateSystemMessageItem("Your preferred genre of story today is: horror.") }, Metadata = { ["foo"] = "bar" }, }; -AgentConversation conversation = await agentsClient.GetConversationClient().CreateConversationAsync(conversationOptions); +ProjectConversation conversation = await projectClient.OpenAI.Conversations.CreateProjectConversationAsync(conversationOptions); // // Add items to an existing conversation to supplement the interaction state // string EXISTING_CONVERSATION_ID = conversation.Id; -_ = await agentsClient.GetConversationClient().CreateConversationItemsAsync( +_ = await projectClient.OpenAI.Conversations.CreateProjectConversationItemsAsync( EXISTING_CONVERSATION_ID, [ResponseItem.CreateSystemMessageItem("Story theme to use: department of licensing.")]); @@ -53,11 +51,8 @@ // Use the agent and conversation in a response // -ResponseCreationOptions responseCreationOptions = new(); -responseCreationOptions.SetAgentReference(AGENT_NAME); -responseCreationOptions.SetConversationReference(EXISTING_CONVERSATION_ID); +ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(newAgentVersion, EXISTING_CONVERSATION_ID); +List items = [ResponseItem.CreateUserMessageItem(inputTextContent: "Tell me a one-line story.")] ; +ResponseResult response = await responseClient.CreateResponseAsync(items); -List items = [ResponseItem.CreateUserMessageItem("Tell me a one-line story.")]; -OpenAIResponse response = await responseClient.CreateResponseAsync(items, responseCreationOptions); - -Console.WriteLine(response.GetOutputText()); \ No newline at end of file +Console.WriteLine(response.GetOutputText()); diff --git a/samples/csharp/quickstart/nuget.config b/samples/csharp/quickstart/nuget.config index bfc4e5c89..90a2bf18c 100644 --- a/samples/csharp/quickstart/nuget.config +++ b/samples/csharp/quickstart/nuget.config @@ -1,6 +1,7 @@ + \ No newline at end of file diff --git a/samples/csharp/quickstart/quickstart-create-agent.cs b/samples/csharp/quickstart/quickstart-create-agent.cs index 75b001d80..dab5d95e2 100644 --- a/samples/csharp/quickstart/quickstart-create-agent.cs +++ b/samples/csharp/quickstart/quickstart-create-agent.cs @@ -3,11 +3,11 @@ using Azure.Identity; string projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT") - ?? throw new InvalidOperationException("Missing environment variable 'PROJECT_ENDPOINT'"); +?? throw new InvalidOperationException("Missing environment variable 'PROJECT_ENDPOINT'"); string modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") - ?? throw new InvalidOperationException("Missing environment variable 'MODEL_DEPLOYMENT_NAME'"); +?? throw new InvalidOperationException("Missing environment variable 'MODEL_DEPLOYMENT_NAME'"); string agentName = Environment.GetEnvironmentVariable("AGENT_NAME") - ?? throw new InvalidOperationException("Missing environment variable 'AGENT_NAME'"); +?? throw new InvalidOperationException("Missing environment variable 'AGENT_NAME'"); AIProjectClient projectClient = new(new Uri(projectEndpoint), new AzureCliCredential()); @@ -20,9 +20,8 @@ agentName, options: new(agentDefinition)); -List agentVersions = projectClient.Agents.GetAgentVersions(agentName); +List agentVersions = [..projectClient.Agents.GetAgentVersions(agentName)]; foreach (AgentVersion agentVersion in agentVersions) { Console.WriteLine($"Agent: {agentVersion.Id}, Name: {agentVersion.Name}, Version: {agentVersion.Version}"); } - diff --git a/samples/csharp/quickstart/quickstart-responses.cs b/samples/csharp/quickstart/quickstart-responses.cs index 1024a0b6d..d980fa97d 100644 --- a/samples/csharp/quickstart/quickstart-responses.cs +++ b/samples/csharp/quickstart/quickstart-responses.cs @@ -1,19 +1,18 @@ using Azure.AI.Projects; using Azure.AI.Projects.OpenAI; using Azure.Identity; -using OpenAI; using OpenAI.Responses; #pragma warning disable OPENAI001 -string projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT") - ?? throw new InvalidOperationException("Missing environment variable 'PROJECT_ENDPOINT'"); -string modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") - ?? throw new InvalidOperationException("Missing environment variable 'MODEL_DEPLOYMENT_NAME'"); +string projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT") +?? throw new InvalidOperationException("Missing environment variable 'PROJECT_ENDPOINT'"); +string modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") +?? throw new InvalidOperationException("Missing environment variable 'MODEL_DEPLOYMENT_NAME'"); -AIProjectClient projectClient = new(new Uri(projectEndpoint ), new AzureCliCredential()); +AIProjectClient projectClient = new(new Uri(projectEndpoint), new AzureCliCredential()); ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForModel(modelDeploymentName); ResponseResult response = await responseClient.CreateResponseAsync("What is the size of France in square miles?"); -Console.WriteLine(response.GetOutputText()); \ No newline at end of file +Console.WriteLine(response.GetOutputText()); diff --git a/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/agent.yaml b/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/agent.yaml index f000e0d35..304b5fcbe 100644 --- a/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/agent.yaml +++ b/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/agent.yaml @@ -24,7 +24,7 @@ template: - name: AZURE_OPENAI_CHAT_DEPLOYMENT_NAME value: "{{chat}}" - name: AZURE_AI_PROJECT_TOOL_CONNECTION_ID - value: + value: MicrosoftLearn resources: - kind: model id: gpt-5 diff --git a/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/main.py b/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/main.py index 4f3f6954c..dc54b4d5d 100644 --- a/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/main.py +++ b/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/main.py @@ -3,11 +3,17 @@ from agent_framework.azure import AzureOpenAIChatClient from azure.ai.agentserver.agentframework import from_agent_framework, FoundryToolsChatMiddleware -from azure.identity import DefaultAzureCredential +from azure.identity import DefaultAzureCredential, get_bearer_token_provider # Load environment variables from .env file for local development # load_dotenv() +# Create a token provider that refreshes tokens automatically for long-running servers +# This avoids 401 errors when the initial token expires (typically after 1 hour) +_credential = DefaultAzureCredential() +_token_provider = get_bearer_token_provider(_credential, "https://cognitiveservices.azure.com/.default") + + def main(): required_env_vars = [ "AZURE_OPENAI_ENDPOINT", @@ -23,7 +29,8 @@ def main(): if project_tool_connection_id := os.environ.get("AZURE_AI_PROJECT_TOOL_CONNECTION_ID"): tools.append({"type": "mcp", "project_connection_id": project_tool_connection_id}) - chat_client = AzureOpenAIChatClient(credential=DefaultAzureCredential(), + # Use token provider for automatic token refresh in long-running servers + chat_client = AzureOpenAIChatClient(ad_token_provider=_token_provider, middleware=FoundryToolsChatMiddleware(tools)) agent = chat_client.create_agent( name="FoundryToolAgent", diff --git a/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/requirements.txt b/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/requirements.txt index cf0d93148..1e93c1a80 100644 --- a/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/agent-with-foundry-tools/requirements.txt @@ -1 +1 @@ -azure-ai-agentserver-agentframework==1.0.0b10 \ No newline at end of file +azure-ai-agentserver-agentframework==1.0.0b12 \ No newline at end of file diff --git a/samples/python/hosted-agents/agent-framework/agent-with-local-tools/requirements.txt b/samples/python/hosted-agents/agent-framework/agent-with-local-tools/requirements.txt index de8089ce8..d094c82ee 100644 --- a/samples/python/hosted-agents/agent-framework/agent-with-local-tools/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/agent-with-local-tools/requirements.txt @@ -1,6 +1,6 @@ +azure-ai-agentserver-agentframework==1.0.0b12 python-dotenv azure-identity -azure-ai-agentserver-agentframework==1.0.0b10 # Azure Monitor / OpenTelemetry azure-monitor-opentelemetry-exporter>=1.0.0b46 diff --git a/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/main.py b/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/main.py index 9a0cfa915..0ed5e61f4 100644 --- a/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/main.py +++ b/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/main.py @@ -9,13 +9,18 @@ from agent_framework import ChatMessage, Context, ContextProvider, Role from agent_framework.azure import AzureOpenAIChatClient from azure.ai.agentserver.agentframework import from_agent_framework # pyright: ignore[reportUnknownVariableType] -from azure.identity import DefaultAzureCredential +from azure.identity import DefaultAzureCredential, get_bearer_token_provider if sys.version_info >= (3, 12): from typing import override else: from typing_extensions import override +# Create a token provider that refreshes tokens automatically for long-running servers +# This avoids 401 errors when the initial token expires (typically after 1 hour) +_credential = DefaultAzureCredential() +_token_provider = get_bearer_token_provider(_credential, "https://cognitiveservices.azure.com/.default") + @dataclass class TextSearchResult: @@ -92,8 +97,9 @@ async def invoking(self, messages: ChatMessage | MutableSequence[ChatMessage], * def create_agent(): - # Create an Agent using the Azure OpenAI Chat Client - agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent( + # Create an Agent using the Azure OpenAI Chat Client with token provider + # for automatic token refresh in long-running servers + agent = AzureOpenAIChatClient(ad_token_provider=_token_provider).create_agent( name="SupportSpecialist", instructions=( "You are a helpful support specialist for Contoso Outdoors. " diff --git a/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/requirements.txt b/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/requirements.txt index cf0d93148..1e93c1a80 100644 --- a/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/agent-with-text-search-rag/requirements.txt @@ -1 +1 @@ -azure-ai-agentserver-agentframework==1.0.0b10 \ No newline at end of file +azure-ai-agentserver-agentframework==1.0.0b12 \ No newline at end of file diff --git a/samples/python/hosted-agents/agent-framework/agents-in-workflow/main.py b/samples/python/hosted-agents/agent-framework/agents-in-workflow/main.py index 78e3cf782..c3ecabfc6 100644 --- a/samples/python/hosted-agents/agent-framework/agents-in-workflow/main.py +++ b/samples/python/hosted-agents/agent-framework/agents-in-workflow/main.py @@ -3,26 +3,31 @@ from agent_framework import ConcurrentBuilder from agent_framework.azure import AzureOpenAIChatClient from azure.ai.agentserver.agentframework import from_agent_framework -from azure.identity import DefaultAzureCredential # pyright: ignore[reportUnknownVariableType] +from azure.identity import DefaultAzureCredential, get_bearer_token_provider # pyright: ignore[reportUnknownVariableType] + +# Create a token provider that refreshes tokens automatically for long-running servers +# This avoids 401 errors when the initial token expires (typically after 1 hour) +_credential = DefaultAzureCredential() +_token_provider = get_bearer_token_provider(_credential, "https://cognitiveservices.azure.com/.default") def create_workflow_builder(): - # Create agents - researcher = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent( + # Create agents using token provider for automatic token refresh + researcher = AzureOpenAIChatClient(ad_token_provider=_token_provider).create_agent( instructions=( "You're an expert market and product researcher. " "Given a prompt, provide concise, factual insights, opportunities, and risks." ), name="researcher", ) - marketer = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent( + marketer = AzureOpenAIChatClient(ad_token_provider=_token_provider).create_agent( instructions=( "You're a creative marketing strategist. " "Craft compelling value propositions and target messaging aligned to the prompt." ), name="marketer", ) - legal = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent( + legal = AzureOpenAIChatClient(ad_token_provider=_token_provider).create_agent( instructions=( "You're a cautious legal/compliance reviewer. " "Highlight constraints, disclaimers, and policy concerns based on the prompt." diff --git a/samples/python/hosted-agents/agent-framework/agents-in-workflow/requirements.txt b/samples/python/hosted-agents/agent-framework/agents-in-workflow/requirements.txt index cf0d93148..1e93c1a80 100644 --- a/samples/python/hosted-agents/agent-framework/agents-in-workflow/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/agents-in-workflow/requirements.txt @@ -1 +1 @@ -azure-ai-agentserver-agentframework==1.0.0b10 \ No newline at end of file +azure-ai-agentserver-agentframework==1.0.0b12 \ No newline at end of file diff --git a/samples/python/hosted-agents/agent-framework/echo-agent/requirements.txt b/samples/python/hosted-agents/agent-framework/echo-agent/requirements.txt index d4a17f84c..9dac56e37 100644 --- a/samples/python/hosted-agents/agent-framework/echo-agent/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/echo-agent/requirements.txt @@ -1,4 +1,4 @@ -azure-ai-agentserver-agentframework==1.0.0b10 +azure-ai-agentserver-agentframework==1.0.0b12 pytest==8.4.2 python-dotenv==1.1.1 azure-monitor-opentelemetry==1.8.1 diff --git a/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/main.py b/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/main.py index 2d5ca5239..c88b3ed56 100644 --- a/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/main.py +++ b/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/main.py @@ -8,7 +8,7 @@ from azure.ai.agentserver.agentframework import from_agent_framework from azure.ai.agentserver.agentframework.persistence.agent_thread_repository import JsonLocalFileAgentThreadRepository -from azure.identity import DefaultAzureCredential +from azure.identity import DefaultAzureCredential, get_bearer_token_provider """ Tool Approvals with Threads @@ -18,6 +18,11 @@ the thread stores and retrieves them automatically. """ +# Create a token provider that refreshes tokens automatically for long-running servers +# This avoids 401 errors when the initial token expires (typically after 1 hour) +_credential = DefaultAzureCredential() +_token_provider = get_bearer_token_provider(_credential, "https://cognitiveservices.azure.com/.default") + class CustomChatMessageStore(ChatMessageStoreProtocol): """Implementation of custom chat message store. In real applications, this can be an implementation of relational database or vector store.""" @@ -63,8 +68,9 @@ def add_to_calendar( def build_agent(): + # Use token provider for automatic token refresh in long-running servers return ChatAgent( - chat_client=AzureOpenAIChatClient(credential=DefaultAzureCredential()), + chat_client=AzureOpenAIChatClient(ad_token_provider=_token_provider), name="CalendarAgent", instructions="You are a helpful calendar assistant.", tools=[add_to_calendar], diff --git a/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/requirements.txt b/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/requirements.txt index f6e956684..1e93c1a80 100644 --- a/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/human-in-the-loop/agent-with-thread-and-hitl/requirements.txt @@ -1 +1 @@ -azure_ai_agentserver_agentframework==1.0.0b9 \ No newline at end of file +azure-ai-agentserver-agentframework==1.0.0b12 \ No newline at end of file diff --git a/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/main.py b/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/main.py index 77ae5c4fa..487a36b14 100644 --- a/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/main.py +++ b/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/main.py @@ -5,7 +5,7 @@ from typing import Any from agent_framework.azure import AzureOpenAIChatClient -from azure.identity import AzureCliCredential +from azure.identity import AzureCliCredential, get_bearer_token_provider from dotenv import load_dotenv from agent_framework import ( # noqa: E402 @@ -24,6 +24,11 @@ from azure.ai.agentserver.agentframework import from_agent_framework from azure.ai.agentserver.agentframework.persistence import FileCheckpointRepository +# Create a token provider that refreshes tokens automatically for long-running servers +# This avoids 401 errors when the initial token expires (typically after 1 hour) +_credential = AzureCliCredential() +_token_provider = get_bearer_token_provider(_credential, "https://cognitiveservices.azure.com/.default") + @dataclass class HumanReviewRequest: """A request message type for escalation to a human reviewer.""" @@ -84,12 +89,13 @@ async def accept_human_review( def create_builder(): # Build a workflow with bidirectional communication between Worker and Reviewer, # and escalation paths for human review. + # Use token provider for automatic token refresh in long-running servers builder = ( WorkflowBuilder() .register_executor( lambda: Worker( id="sub-worker", - chat_client=AzureOpenAIChatClient(credential=AzureCliCredential()), + chat_client=AzureOpenAIChatClient(ad_token_provider=_token_provider), ), name="worker", ) diff --git a/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/requirements.txt b/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/requirements.txt index adac06de2..1e93c1a80 100644 --- a/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/human-in-the-loop/workflow-agent-with-checkpoint-and-hitl/requirements.txt @@ -1 +1 @@ -azure-ai-agentserver-agentframework==1.0.0b9 \ No newline at end of file +azure-ai-agentserver-agentframework==1.0.0b12 \ No newline at end of file diff --git a/samples/python/hosted-agents/agent-framework/web-search-agent/requirements.txt b/samples/python/hosted-agents/agent-framework/web-search-agent/requirements.txt index d4a17f84c..9dac56e37 100644 --- a/samples/python/hosted-agents/agent-framework/web-search-agent/requirements.txt +++ b/samples/python/hosted-agents/agent-framework/web-search-agent/requirements.txt @@ -1,4 +1,4 @@ -azure-ai-agentserver-agentframework==1.0.0b10 +azure-ai-agentserver-agentframework==1.0.0b12 pytest==8.4.2 python-dotenv==1.1.1 azure-monitor-opentelemetry==1.8.1 diff --git a/samples/python/hosted-agents/custom/system-utility-agent/requirements.txt b/samples/python/hosted-agents/custom/system-utility-agent/requirements.txt index e54f2ac67..f0b792a40 100644 --- a/samples/python/hosted-agents/custom/system-utility-agent/requirements.txt +++ b/samples/python/hosted-agents/custom/system-utility-agent/requirements.txt @@ -1,6 +1,6 @@ azure-identity==1.25.1 azure-ai-projects==2.0.0b2 -azure-ai-agentserver-core==1.0.0b10 +azure-ai-agentserver-core==1.0.0b12 openai==2.14.0 python-dotenv==1.0.0 psutil==5.9.4 diff --git a/samples/python/hosted-agents/langgraph/calculator-agent/requirements.txt b/samples/python/hosted-agents/langgraph/calculator-agent/requirements.txt index 01e3547ab..c96237247 100644 --- a/samples/python/hosted-agents/langgraph/calculator-agent/requirements.txt +++ b/samples/python/hosted-agents/langgraph/calculator-agent/requirements.txt @@ -1 +1 @@ -azure-ai-agentserver-langgraph==1.0.0b10 +azure-ai-agentserver-langgraph==1.0.0b12 diff --git a/samples/python/hosted-agents/langgraph/human-in-the-loop/requirements.txt b/samples/python/hosted-agents/langgraph/human-in-the-loop/requirements.txt index a95dd7516..c96237247 100644 --- a/samples/python/hosted-agents/langgraph/human-in-the-loop/requirements.txt +++ b/samples/python/hosted-agents/langgraph/human-in-the-loop/requirements.txt @@ -1 +1 @@ -azure-ai-agentserver-langgraph==1.0.0b9 +azure-ai-agentserver-langgraph==1.0.0b12 diff --git a/samples/python/hosted-agents/langgraph/react-agent-with-foundry-tools/requirements.txt b/samples/python/hosted-agents/langgraph/react-agent-with-foundry-tools/requirements.txt index 446acb1d6..251a1a754 100644 --- a/samples/python/hosted-agents/langgraph/react-agent-with-foundry-tools/requirements.txt +++ b/samples/python/hosted-agents/langgraph/react-agent-with-foundry-tools/requirements.txt @@ -1 +1 @@ -azure-ai-agentserver-langgraph==1.0.0b10 \ No newline at end of file +azure-ai-agentserver-langgraph==1.0.0b12 \ No newline at end of file