diff --git a/dotnet/agent-framework-dotnet.slnx b/dotnet/agent-framework-dotnet.slnx index 9801ccc105..e080113df2 100644 --- a/dotnet/agent-framework-dotnet.slnx +++ b/dotnet/agent-framework-dotnet.slnx @@ -119,6 +119,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/Program.cs b/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/Program.cs index cbbc327948..4278c301af 100644 --- a/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/Program.cs +++ b/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/Program.cs @@ -16,10 +16,7 @@ persistentAgentsClientOptions.Retry.NetworkTimeout = TimeSpan.FromMinutes(20); // Get a client to create/retrieve server side agents with. -// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. -// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid -// latency issues, unintended credential probing, and potential security risks from fallback mechanisms. -PersistentAgentsClient persistentAgentsClient = new(endpoint, new DefaultAzureCredential(), persistentAgentsClientOptions); +PersistentAgentsClient persistentAgentsClient = new(endpoint, new AzureCliCredential(), persistentAgentsClientOptions); // Define and configure the Deep Research tool. DeepResearchToolDefinition deepResearchTool = new(new DeepResearchDetails( diff --git a/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/README.md b/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/README.md index dc24ba4554..1848b10826 100644 --- a/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/README.md +++ b/dotnet/samples/02-agents/Agents/Agent_Step15_DeepResearch/README.md @@ -23,12 +23,14 @@ Before running this sample, ensure you have: Pay special attention to the purple `Note` boxes in the Azure documentation. -**Note**: The Bing Connection ID must be from the **project**, not the resource. It has the following format: +**Note**: The Bing Grounding Connection ID must be the **full ARM resource URI** from the project, not just the connection name. It has the following format: ``` -/subscriptions//resourceGroups//providers//accounts//projects//connections/ +/subscriptions//resourceGroups//providers/Microsoft.CognitiveServices/accounts//projects//connections/ ``` +You can find this in the Azure AI Foundry portal under **Management > Connected resources**, or retrieve it programmatically via the connections API (`.id` property). + ## Environment Variables Set the following environment variables: @@ -37,8 +39,8 @@ Set the following environment variables: # Replace with your Azure AI Foundry project endpoint $env:AZURE_AI_PROJECT_ENDPOINT="https://your-project.services.ai.azure.com/" -# Replace with your Bing connection ID from the project -$env:AZURE_AI_BING_CONNECTION_ID="/subscriptions/.../connections/your-bing-connection" +# Replace with your Bing Grounding connection ID (full ARM resource URI) +$env:AZURE_AI_BING_CONNECTION_ID="/subscriptions//resourceGroups//providers/Microsoft.CognitiveServices/accounts//projects//connections/" # Optional, defaults to o3-deep-research $env:AZURE_AI_REASONING_DEPLOYMENT_NAME="o3-deep-research" diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/Program.cs index 1e1e48d54b..f2224b740f 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/Program.cs @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. -// This sample demonstrates how to use Azure AI Foundry's Red Teaming service to assess +// This sample demonstrates how to use Microsoft Foundry's Red Teaming service to assess // the safety and resilience of an AI model against adversarial attacks. // // It uses the RedTeam API from Azure.AI.Projects to run automated attack simulations @@ -88,7 +88,7 @@ Console.WriteLine($" Status: {redTeamRun.Status}"); Console.WriteLine(); - Console.WriteLine("Review the detailed results in the Azure AI Foundry portal:"); + Console.WriteLine("Review the detailed results in the Microsoft Foundry portal:"); Console.WriteLine($" {endpoint}"); } else diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/README.md index 24e4a62b35..2fcc3d1efc 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/README.md @@ -1,9 +1,9 @@ -# Red Teaming with Azure AI Foundry (Classic) +# Red Teaming with Microsoft Foundry (Classic) > [!IMPORTANT] -> This sample uses the **classic Azure AI Foundry** red teaming API (`/redTeams/runs`) via `Azure.AI.Projects`. Results are viewable in the classic Foundry portal experience. The **new Foundry** portal's red teaming feature uses a different evaluation-based API that is not yet available in the .NET SDK. +> This sample uses the **classic Microsoft Foundry** red teaming API (`/redTeams/runs`) via `Azure.AI.Projects`. Results are viewable in the classic Foundry portal experience. The **new Foundry** portal's red teaming feature uses a different evaluation-based API that is not yet available in the .NET SDK. -This sample demonstrates how to use Azure AI Foundry's Red Teaming service to assess the safety and resilience of an AI model against adversarial attacks. +This sample demonstrates how to use Microsoft Foundry's Red Teaming service to assess the safety and resilience of an AI model against adversarial attacks. ## What this sample demonstrates @@ -11,14 +11,14 @@ This sample demonstrates how to use Azure AI Foundry's Red Teaming service to as - Using multiple `AttackStrategy` options (Easy, Moderate, Jailbreak) - Evaluating across `RiskCategory` categories (Violence, HateUnfairness, Sexual, SelfHarm) - Submitting a red team scan and polling for completion -- Reviewing results in the Azure AI Foundry portal +- Reviewing results in the Microsoft Foundry portal ## Prerequisites Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure AI Foundry project (hub and project created) +- Microsoft Foundry project (hub and project created) - Azure OpenAI deployment (e.g., gpt-4o or gpt-4o-mini) - Azure CLI installed and authenticated (for Azure credential authentication) @@ -32,7 +32,7 @@ Red teaming is only available in regions that support risk and safety evaluators Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-project.services.ai.azure.com/api/projects/your-project" # Replace with your Azure Foundry project endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-project.services.ai.azure.com/api/projects/your-project" # Replace with your Microsoft Foundry project endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` @@ -51,9 +51,9 @@ The sample will: 1. Configure a `RedTeam` run targeting the specified model deployment 2. Define risk categories and attack strategies -3. Submit the scan to Azure AI Foundry's Red Teaming service +3. Submit the scan to Microsoft Foundry's Red Teaming service 4. Poll for completion (this may take several minutes) -5. Display the run status and direct you to the Azure AI Foundry portal for detailed results +5. Display the run status and direct you to the Microsoft Foundry portal for detailed results ## Understanding Red Teaming @@ -76,7 +76,7 @@ The sample will: ### Interpreting Results -- Results are available in the Azure AI Foundry portal (**classic view** — toggle at top-right) under the red teaming section +- Results are available in the Microsoft Foundry portal (**classic view** — toggle at top-right) under the red teaming section - Lower Attack Success Rate (ASR) is better — target ASR < 5% for production - Review individual attack conversations to understand vulnerabilities @@ -85,7 +85,7 @@ The sample will: > [!NOTE] > - The .NET Red Teaming API (`Azure.AI.Projects`) currently supports targeting **model deployments only** via `AzureOpenAIModelConfiguration`. The `AzureAIAgentTarget` type exists in the SDK but is consumed by the **Evaluation Taxonomy** API (`/evaluationtaxonomies`), not by the Red Teaming API (`/redTeams/runs`). > - Agent-targeted red teaming with agent-specific risk categories (Prohibited actions, Sensitive data leakage, Task adherence) is documented in the [concept docs](https://learn.microsoft.com/azure/ai-foundry/concepts/ai-red-teaming-agent) but is not yet available via the public REST API or .NET SDK. -> - Results from this API appear in the **classic** Azure AI Foundry portal view. The new Foundry portal uses a separate evaluation-based system with `eval_*` identifiers. +> - Results from this API appear in the **classic** Microsoft Foundry portal view. The new Foundry portal uses a separate evaluation-based system with `eval_*` identifiers. ## Related Resources diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/Program.cs index 8f8c9fa4ee..379f600b64 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample demonstrates how to use Microsoft.Extensions.AI.Evaluation.Quality to evaluate // an Agent Framework agent's response quality with a self-reflection loop. @@ -46,7 +46,7 @@ .GetChatClient(evaluatorDeploymentName) .AsIChatClient(); -// Configure evaluation: quality evaluators use the LLM, safety evaluators use Azure AI Foundry +// Configure evaluation: quality evaluators use the LLM, safety evaluators use Microsoft Foundry ContentSafetyServiceConfiguration safetyConfig = new( credential: credential, endpoint: new Uri(endpoint)); @@ -64,11 +64,11 @@ // Example question and grounding context const string Question = """ - What are the main benefits of using Azure AI Foundry for building AI applications? + What are the main benefits of using Microsoft Foundry for building AI applications? """; const string Context = """ - Azure AI Foundry is a comprehensive platform for building, deploying, and managing AI applications. + Microsoft Foundry is a comprehensive platform for building, deploying, and managing AI applications. Key benefits include: 1. Unified development environment with support for multiple AI frameworks and models 2. Built-in safety and security features including content filtering and red teaming tools diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/README.md index d71eeca6af..66696809bc 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Evaluations_Step02_SelfReflection/README.md @@ -17,11 +17,11 @@ For details on the self-reflection approach, see [Reflexion: Language Agents wit Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure AI Foundry project (hub and project created) +- Microsoft Foundry project (hub and project created) - Azure OpenAI deployment (e.g., gpt-4o or gpt-4o-mini) - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). ### Azure Resources Required @@ -37,7 +37,7 @@ Before you begin, ensure you have the following prerequisites: Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-project.api.azureml.ms" # Azure Foundry project endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-project.api.azureml.ms" # Microsoft Foundry project endpoint $env:AZURE_OPENAI_ENDPOINT="https://your-openai.openai.azure.com/" # Azure OpenAI endpoint (for quality evaluators) $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Model deployment name ``` @@ -108,7 +108,7 @@ The `GroundednessEvaluator` measures how well the agent's response is grounded i - [Reflexion Paper (NeurIPS 2023)](https://arxiv.org/abs/2303.11366) - [Microsoft.Extensions.AI.Evaluation Libraries](https://learn.microsoft.com/dotnet/ai/evaluation/libraries) - [GroundednessEvaluator API Reference](https://learn.microsoft.com/dotnet/api/microsoft.extensions.ai.evaluation.quality.groundednessevaluator) -- [Azure AI Foundry Evaluation Service](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/evaluate-sdk) +- [Microsoft Foundry Evaluation Service](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/evaluate-sdk) ## Next Steps diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/Program.cs index 72676bed45..cdbfbfbc9b 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/Program.cs @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. -// This sample shows how to create and use AI agents with Azure Foundry Agents as the backend. +// This sample shows how to create and use AI agents with Microsoft Foundry Agents as the backend. using Azure.AI.Projects; using Azure.AI.Projects.OpenAI; @@ -12,7 +12,7 @@ const string JokerName = "JokerAgent"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/README.md index ce5eca8277..5bf1d15751 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.1_Basics/README.md @@ -1,6 +1,6 @@ # Creating and Managing AI Agents with Versioning -This sample demonstrates how to create and manage AI agents with Azure Foundry Agents, including: +This sample demonstrates how to create and manage AI agents with Microsoft Foundry Agents, including: - Creating agents with different versions - Retrieving agents by version or latest version - Running multi-turn conversations with agents @@ -11,15 +11,15 @@ This sample demonstrates how to create and manage AI agents with Azure Foundry A Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs index dd5db03b15..297244bb62 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. -// This sample shows how to create and use a simple AI agent with Azure Foundry Agents as the backend. +// This sample shows how to create and use a simple AI agent with Microsoft Foundry Agents as the backend. using Azure.AI.Projects; using Azure.AI.Projects.OpenAI; @@ -13,7 +13,7 @@ const string JokerInstructions = "You are good at telling jokes."; const string JokerName = "JokerAgent"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/README.md index 40cb5e107d..34b53f25df 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step01.2_Running/README.md @@ -1,6 +1,6 @@ # Running a Simple AI Agent with Streaming -This sample demonstrates how to create and run a simple AI agent with Azure Foundry Agents, including both text and streaming responses. +This sample demonstrates how to create and run a simple AI agent with Microsoft Foundry Agents, including both text and streaming responses. ## What this sample demonstrates @@ -14,15 +14,15 @@ This sample demonstrates how to create and run a simple AI agent with Azure Foun Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs index 1ac51c30ad..5895d19492 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to create and use a simple AI agent with a multi-turn conversation. @@ -13,7 +13,7 @@ const string JokerInstructions = "You are good at telling jokes."; const string JokerName = "JokerAgent"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/README.md index 86721bf960..30764a0a02 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/README.md @@ -16,15 +16,15 @@ This sample demonstrates how to implement multi-turn conversations with AI agent Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` @@ -42,7 +42,7 @@ dotnet run --project .\FoundryAgents_Step02_MultiturnConversation The sample will: 1. Create an agent named "JokerAgent" with instructions to tell jokes -2. Create a project conversation to enable visibility in the Azure Foundry UI +2. Create a project conversation to enable visibility in the Microsoft Foundry UI 3. Create a thread linked to the conversation ID for context tracking 4. Run the agent with a text prompt and display the response 5. Send a follow-up message to the same thread, demonstrating context preservation @@ -54,6 +54,6 @@ The sample will: When working with multi-turn conversations, there are two approaches: -- **With Conversation ID**: By passing a `conversation.Id` to `CreateSessionAsync()`, the conversation will be visible in the Azure Foundry Project UI. This is useful for tracking and debugging conversations. +- **With Conversation ID**: By passing a `conversation.Id` to `CreateSessionAsync()`, the conversation will be visible in the Microsoft Foundry Project UI. This is useful for tracking and debugging conversations. - **Without Conversation ID**: Sessions created without a conversation ID still work correctly, maintaining context via `PreviousResponseId`. However, these conversations may not appear in the Foundry UI. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs index cfd74000a6..e1645885f0 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample demonstrates how to use an agent with function tools. // It shows both non-streaming and streaming agent interactions using weather-related tools. @@ -19,7 +19,7 @@ static string GetWeather([Description("The location to get the weather for.")] s const string AssistantInstructions = "You are a helpful assistant that can get weather information."; const string AssistantName = "WeatherAssistant"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/README.md index fa9b5baf21..7f413698d0 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/README.md @@ -15,15 +15,15 @@ This sample demonstrates how to use function tools with AI agents, allowing agen Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs index f33fae35f4..b2ecdb719f 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample demonstrates how to use an agent with function tools that require a human in the loop for approvals. // It shows both non-streaming and streaming agent interactions using weather-related tools. @@ -22,7 +22,7 @@ static string GetWeather([Description("The location to get the weather for.")] s const string AssistantInstructions = "You are a helpful assistant that can get weather information."; const string AssistantName = "WeatherAssistant"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/README.md index 42cbd6ba32..e671653af9 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/README.md @@ -15,15 +15,15 @@ This sample demonstrates how to use function tools that require human approval b Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs index 3c02a4cec2..3add6e5fb1 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to configure an agent to produce structured output. @@ -18,7 +18,7 @@ const string AssistantInstructions = "You are a helpful assistant that extracts structured information about people."; const string AssistantName = "StructuredOutputAssistant"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/README.md index 4c44230e18..489cd95c8c 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step05_StructuredOutput/README.md @@ -15,15 +15,15 @@ This sample demonstrates how to configure AI agents to produce structured output Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/Program.cs index d8a5a7cd35..303ba8fd77 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to create and use a simple AI agent with a conversation that can be persisted to disk. @@ -13,7 +13,7 @@ const string JokerInstructions = "You are good at telling jokes."; const string JokerName = "JokerAgent"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/README.md index 57a032e9ec..bcf0a5f320 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step06_PersistedConversations/README.md @@ -15,15 +15,15 @@ This sample demonstrates how to serialize and persist agent conversation threads Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs index 257e24859f..94a199e089 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. -// This sample shows how to create and use a simple AI agent with Azure Foundry Agents as the backend that logs telemetry using OpenTelemetry. +// This sample shows how to create and use a simple AI agent with Microsoft Foundry Agents as the backend that logs telemetry using OpenTelemetry. using Azure.AI.Projects; using Azure.Identity; @@ -28,7 +28,7 @@ } using var tracerProvider = tracerProviderBuilder.Build(); -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/README.md index 459434bce2..08e36a4125 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step07_Observability/README.md @@ -16,16 +16,16 @@ This sample demonstrates how to add observability to AI agents using OpenTelemet Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) - (Optional) Application Insights connection string for Azure Monitor integration -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini $env:APPLICATIONINSIGHTS_CONNECTION_STRING="your-connection-string" # Optional, for Azure Monitor integration ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step08_DependencyInjection/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step08_DependencyInjection/README.md index 12760e736f..10a465cf2f 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step08_DependencyInjection/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step08_DependencyInjection/README.md @@ -16,15 +16,15 @@ This sample demonstrates how to use dependency injection to register and manage Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/Program.cs index e1968122a4..342c18eb27 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to expose an AI agent as an MCP tool. @@ -24,7 +24,7 @@ // Retrieve the list of tools available on the GitHub server IList mcpTools = await mcpClient.ListToolsAsync(); string agentName = "AgentWithMCP"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/README.md index e4e3fe537a..fab1df7523 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step09_UsingMcpClientAsTools/README.md @@ -15,16 +15,16 @@ This sample demonstrates how to use Model Context Protocol (MCP) client tools wi Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) - Node.js and npm installed (for running the GitHub MCP server) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs index d44d62df51..bcd912ee0c 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use Image Multi-Modality with an AI agent. @@ -13,7 +13,7 @@ const string VisionInstructions = "You are a helpful agent that can analyze images"; const string VisionName = "VisionAgent"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/README.md index 220104a291..b6982c665a 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step10_UsingImages/README.md @@ -1,6 +1,6 @@ # Using Images with AI Agents -This sample demonstrates how to use image multi-modality with an AI agent. It shows how to create a vision-enabled agent that can analyze and describe images using Azure Foundry Agents. +This sample demonstrates how to use image multi-modality with an AI agent. It shows how to create a vision-enabled agent that can analyze and describe images using Microsoft Foundry Agents. ## What this sample demonstrates @@ -14,7 +14,7 @@ This sample demonstrates how to use image multi-modality with an AI agent. It sh - **Vision Agent**: Creates an agent specifically instructed to analyze images - **Multimodal Input**: Combines text questions with image URI in a single message -- **Azure Foundry Agents Integration**: Uses Azure Foundry Agents with vision capabilities +- **Microsoft Foundry Agents Integration**: Uses Microsoft Foundry Agents with vision capabilities ## Prerequisites @@ -29,7 +29,7 @@ Before running this sample, ensure you have: Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-resource.openai.azure.com/" # Replace with your Azure Foundry Project endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-resource.openai.azure.com/" # Replace with your Microsoft Foundry Project endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o" # Replace with your model deployment name (optional, defaults to gpt-4o) ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/Program.cs index 585725322e..b0ead2e763 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/Program.cs @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. -// This sample shows how to create and use an Azure Foundry Agents AI agent as a function tool. +// This sample shows how to create and use an Microsoft Foundry Agents AI agent as a function tool. using System.ComponentModel; using Azure.AI.Projects; @@ -20,7 +20,7 @@ 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."; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/README.md index 5da59b6edb..8166f656fb 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step11_AsFunctionTool/README.md @@ -15,15 +15,15 @@ This sample demonstrates how to expose an AI agent as a function tool, enabling Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs index 7ea6bc88a3..d921c73faf 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. -// This sample shows multiple middleware layers working together with Azure Foundry Agents: +// This sample shows multiple middleware layers working together with Microsoft Foundry Agents: // agent run (PII filtering and guardrails), // function invocation (logging and result overrides), and human-in-the-loop // approval workflows for sensitive function calls. @@ -12,14 +12,14 @@ using Microsoft.Agents.AI; using Microsoft.Extensions.AI; -// Get Azure AI Foundry configuration from environment variables +// Get Microsoft Foundry configuration from environment variables string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); string deploymentName = System.Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o"; const string AssistantInstructions = "You are an AI assistant that helps people find information."; const string AssistantName = "InformationAssistant"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/README.md index 96d12d9828..2bfd84fb70 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step12_Middleware/README.md @@ -4,7 +4,7 @@ This sample demonstrates how to add middleware to intercept agent runs and funct ## What This Sample Shows -1. Azure Foundry Agents integration via `AIProjectClient` and `DefaultAzureCredential` +1. Microsoft Foundry Agents integration via `AIProjectClient` and `DefaultAzureCredential` 2. Agent run middleware (logging and monitoring) 3. Function invocation middleware (logging and overriding tool results) 4. Per-request agent run middleware @@ -22,15 +22,15 @@ Attempting to use function middleware on agents that do not wrap a ChatClientAge Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/Program.cs index 244d83d632..cdd11de520 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use plugins with an AI agent. Plugin classes can // depend on other services that need to be injected. In this sample, the @@ -29,7 +29,7 @@ IServiceProvider serviceProvider = services.BuildServiceProvider(); -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/README.md index 5c52ffcd1c..cf89416fd3 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step13_Plugins/README.md @@ -15,15 +15,15 @@ This sample demonstrates how to use plugins with AI agents, where plugins are se Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs index 854d317495..7c459a06d5 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use Code Interpreter Tool with AI Agents. @@ -18,7 +18,7 @@ const string AgentNameMEAI = "CoderAgent-MEAI"; const string AgentNameNative = "CoderAgent-NATIVE"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/README.md index 34fa18c94c..d5df9fc3e2 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/README.md @@ -16,15 +16,15 @@ This sample demonstrates how to use the code interpreter tool with AI agents. Th Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs index 1c5510218a..465e50c3ed 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use Computer Use Tool with AI Agents. @@ -21,7 +21,7 @@ private static async Task Main(string[] args) // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. - // Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. + // Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential()); const string AgentInstructions = @" You are a computer automation assistant. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/README.md index 092f2bd1cf..023b377ad0 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step15_ComputerUse/README.md @@ -27,15 +27,15 @@ This sample demonstrates how to use the computer use tool with AI agents. The co Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="computer-use-preview" # Optional, defaults to computer-use-preview ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/Program.cs index 36f28c2387..f9a9e98c45 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use File Search Tool with AI Agents. @@ -16,7 +16,7 @@ const string AgentInstructions = "You are a helpful assistant that can search through uploaded files to answer questions."; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/README.md index db74868d3d..731dc75d35 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step16_FileSearch/README.md @@ -16,15 +16,15 @@ This sample demonstrates how to use the file search tool with AI agents. The fil Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses `DefaultAzureCredential` for authentication. For local development, make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure Identity documentation](https://learn.microsoft.com/dotnet/api/azure.identity.defaultazurecredential). +**Note**: This demo uses `DefaultAzureCredential` for authentication. For local development, make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure Identity documentation](https://learn.microsoft.com/dotnet/api/azure.identity.defaultazurecredential). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` @@ -42,7 +42,7 @@ dotnet run --project .\FoundryAgents_Step16_FileSearch The sample will: 1. Create a temporary text file with employee directory information -2. Upload the file to Azure Foundry +2. Upload the file to Microsoft Foundry 3. Create a vector store with the uploaded file 4. Create an agent with file search capabilities using one of: - Option 1: Using HostedFileSearchTool (MEAI abstraction) diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/Program.cs index 2ee5a94458..fff4fc247b 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use OpenAPI Tools with AI Agents. @@ -68,7 +68,7 @@ } """; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential()); // Create the OpenAPI function definition diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/README.md index a859f6b963..03e8728f9e 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step17_OpenAPITools/README.md @@ -15,15 +15,15 @@ This sample demonstrates how to use OpenAPI tools with AI agents. OpenAPI tools Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses `DefaultAzureCredential` for authentication, which supports multiple authentication methods including Azure CLI, managed identity, and more. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure Identity documentation](https://learn.microsoft.com/dotnet/api/azure.identity.defaultazurecredential). +**Note**: This demo uses `DefaultAzureCredential` for authentication, which supports multiple authentication methods including Azure CLI, managed identity, and more. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure Identity documentation](https://learn.microsoft.com/dotnet/api/azure.identity.defaultazurecredential). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/Program.cs index 365bf6ed08..3d9e8661f6 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use Bing Custom Search Tool with AI Agents. @@ -18,7 +18,7 @@ You are a helpful agent that can use Bing Custom Search tools to assist users. Use the available Bing Custom Search tools to answer questions and perform tasks. """; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/README.md index ccc1873a04..37fb19b5b1 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step18_BingCustomSearch/README.md @@ -24,25 +24,25 @@ Both options produce the same result. Toggle between them by commenting/uncommen Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) - A Bing Custom Search resource configured in Azure and connected to your Foundry project -**Note**: This demo uses Azure Default credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. +**Note**: This demo uses Azure Default credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. Set the following environment variables: ```powershell -$env:AZURE_FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" -$env:AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini -$env:BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID="/subscriptions//resourceGroups//providers/Microsoft.CognitiveServices/accounts//projects//connections/" -$env:BING_CUSTOM_SEARCH_INSTANCE_NAME="your-configuration-name" +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini +$env:AZURE_AI_CUSTOM_SEARCH_CONNECTION_ID="/subscriptions//resourceGroups//providers/Microsoft.CognitiveServices/accounts//projects//connections/" +$env:AZURE_AI_CUSTOM_SEARCH_INSTANCE_NAME="your-configuration-name" ``` ### Finding the connection ID and instance name -- **Connection ID**: The full ARM resource path including the `/projects//connections/` segment. Find the connection name in your Foundry project under **Management center** → **Connected resources**. -- **Instance Name**: The **configuration name** from the Bing Custom Search resource (Azure portal → your Bing Custom Search resource → **Configurations**). This is _not_ the Azure resource name. +- **Connection ID** (`AZURE_AI_CUSTOM_SEARCH_CONNECTION_ID`): The full ARM resource URI including the `/projects//connections/` segment. Find the connection name in your Foundry project under **Management center** → **Connected resources**. +- **Instance Name** (`AZURE_AI_CUSTOM_SEARCH_INSTANCE_NAME`): The **configuration name** from your Bing Custom Search resource (Azure portal → your Bing Custom Search resource → **Configurations**). This is _not_ the Azure resource name or the connection name — it's the name of the specific search configuration that defines which domains/sites to search against. ## Run the sample diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/Program.cs index 6d1daf85df..379b08b808 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use SharePoint Grounding Tool with AI Agents. @@ -8,8 +8,8 @@ using Microsoft.Agents.AI; using OpenAI.Responses; -string endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set."); -string deploymentName = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; string sharepointConnectionId = Environment.GetEnvironmentVariable("SHAREPOINT_PROJECT_CONNECTION_ID") ?? throw new InvalidOperationException("SHAREPOINT_PROJECT_CONNECTION_ID is not set."); const string AgentInstructions = """ @@ -17,7 +17,7 @@ You are a helpful agent that can use SharePoint tools to assist users. Use the available SharePoint tools to answer questions and perform tasks. """; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/README.md index ccbd699011..35ad02b37f 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step19_SharePoint/README.md @@ -14,18 +14,18 @@ This sample demonstrates how to use the SharePoint grounding tool with AI agents Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure authentication configured for `DefaultAzureCredential` (for example, Azure CLI logged in with `az login`, environment variables, managed identity, or IDE sign-in) -- A SharePoint project connection configured in Azure Foundry +- A SharePoint project connection configured in Microsoft Foundry -**Note**: This demo uses `DefaultAzureCredential` for authentication. This credential will try multiple authentication mechanisms in order (such as environment variables, managed identity, Azure CLI login, and IDE sign-in) and use the first one that works. A common option for local development is to sign in with the Azure CLI using `az login` and ensure you have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively) and the [DefaultAzureCredential documentation](https://learn.microsoft.com/dotnet/api/azure.identity.defaultazurecredential). +**Note**: This demo uses `DefaultAzureCredential` for authentication. This credential will try multiple authentication mechanisms in order (such as environment variables, managed identity, Azure CLI login, and IDE sign-in) and use the first one that works. A common option for local development is to sign in with the Azure CLI using `az login` and ensure you have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively) and the [DefaultAzureCredential documentation](https://learn.microsoft.com/dotnet/api/azure.identity.defaultazurecredential). Set the following environment variables: ```powershell -$env:AZURE_FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint -$env:AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini -$env:SHAREPOINT_PROJECT_CONNECTION_ID="your-sharepoint-connection-id" # Required: SharePoint project connection ID +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini +$env:SHAREPOINT_PROJECT_CONNECTION_ID="your-sharepoint-connection-id" # Required: The full ARM resource URI, e.g., "/subscriptions/.../connections/SharepointTestTool" ``` ## Run the sample diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/Program.cs index 2f13c2c30c..e106beb543 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use Microsoft Fabric Tool with AI Agents. @@ -8,13 +8,13 @@ using Microsoft.Agents.AI; using OpenAI.Responses; -string endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set."); -string deploymentName = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; string fabricConnectionId = Environment.GetEnvironmentVariable("FABRIC_PROJECT_CONNECTION_ID") ?? throw new InvalidOperationException("FABRIC_PROJECT_CONNECTION_ID is not set."); const string AgentInstructions = "You are a helpful assistant with access to Microsoft Fabric data. Answer questions based on data available through your Fabric connection."; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/README.md index a5faf79d9d..bb51adbb0d 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step20_MicrosoftFabric/README.md @@ -23,18 +23,18 @@ Both options produce the same result. Toggle between them by commenting/uncommen Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -- A Microsoft Fabric workspace with a configured project connection in Azure Foundry +- A Microsoft Fabric workspace with a configured project connection in Microsoft Foundry -**Note**: This demo uses Azure Default credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. +**Note**: This demo uses Azure Default credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. Set the following environment variables: ```powershell -$env:AZURE_FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" -$env:AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini -$env:FABRIC_PROJECT_CONNECTION_ID="your-fabric-connection-id" # The Fabric project connection ID from Azure Foundry +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini +$env:FABRIC_PROJECT_CONNECTION_ID="your-fabric-connection-id" # The full ARM resource URI, e.g., "/subscriptions/.../connections/FabricTestTool" ``` ## Run the sample diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/Program.cs index 1ac312ddae..35f9d09da3 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. // This sample shows how to use the Responses API Web Search Tool with AI Agents. @@ -15,7 +15,7 @@ const string AgentInstructions = "You are a helpful assistant that can search the web to find current information and answer questions accurately."; const string AgentName = "WebSearchAgent"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential()); // Option 1 - Using HostedWebSearchTool (MEAI + AgentFramework) diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/README.md index 8da390878c..3b8d410598 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step21_WebSearch/README.md @@ -15,7 +15,7 @@ This sample demonstrates how to use the Responses API web search tool with AI ag Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure authentication configured for `DefaultAzureCredential` (for example, Azure CLI logged in with `az login`, environment variables, managed identity, or IDE sign-in) **Note**: This sample authenticates using `DefaultAzureCredential` from the Azure Identity library, which will try several credential sources (including Azure CLI, environment variables, managed identity, and IDE sign-in). Ensure at least one supported credential source is available. For more information, see the [Azure Identity documentation](https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme). @@ -25,8 +25,8 @@ Before you begin, ensure you have the following prerequisites: Set the following environment variables: ```powershell -$env:AZURE_FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint -$env:AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` ## Run the sample diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/Program.cs index 836bf1b684..bce0ce0d78 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/Program.cs @@ -12,11 +12,8 @@ string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; - -// Memory store configuration -// NOTE: Memory stores must be created beforehand via Azure Portal or Python SDK. -// The .NET SDK currently only supports using existing memory stores with agents. -string memoryStoreName = Environment.GetEnvironmentVariable("AZURE_AI_MEMORY_STORE_ID") ?? throw new InvalidOperationException("AZURE_AI_MEMORY_STORE_ID is not set."); +string embeddingModelName = Environment.GetEnvironmentVariable("AZURE_AI_EMBEDDING_DEPLOYMENT_NAME") ?? "text-embedding-ada-002"; +string memoryStoreName = Environment.GetEnvironmentVariable("AZURE_AI_MEMORY_STORE_ID") ?? $"foundry-memory-sample-{Guid.NewGuid():N}"; const string AgentInstructions = """ You are a helpful assistant that remembers past conversations. @@ -27,76 +24,91 @@ Use the memory search tool to recall relevant information from previous interact const string AgentNameMEAI = "MemorySearchAgent-MEAI"; const string AgentNameNative = "MemorySearchAgent-NATIVE"; -// Scope identifies the user or context for memory isolation. -// Using a unique user identifier ensures memories are private to that user. string userScope = $"user_{Environment.MachineName}"; -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. -AIProjectClient aiProjectClient = new(new Uri(endpoint), new AzureCliCredential()); +DefaultAzureCredential credential = new(); +AIProjectClient aiProjectClient = new(new Uri(endpoint), credential); -// Create the Memory Search tool configuration -MemorySearchPreviewTool memorySearchTool = new(memoryStoreName, userScope) -{ - // Optional: Configure how quickly new memories are indexed (in seconds) - UpdateDelay = 1, +// Ensure the memory store exists and has memories to retrieve. +await EnsureMemoryStoreAsync(); - // Optional: Configure search behavior - SearchOptions = new MemorySearchToolOptions - { - // Additional search options can be configured here if needed - } -}; +MemorySearchPreviewTool memorySearchTool = new(memoryStoreName, userScope) { UpdateDelay = 0 }; // Create agent using Option 1 (MEAI) or Option 2 (Native SDK) AIAgent agent = await CreateAgentWithMEAI(); // AIAgent agent = await CreateAgentWithNativeSDK(); -Console.WriteLine("Agent created with Memory Search tool. Starting conversation...\n"); - -// Conversation 1: Share some personal information -Console.WriteLine("User: My name is Alice and I love programming in C#."); -AgentResponse response1 = await agent.RunAsync("My name is Alice and I love programming in C#."); -Console.WriteLine($"Agent: {response1.Messages.LastOrDefault()?.Text}\n"); - -// Allow time for memory to be indexed -await Task.Delay(2000); +try +{ + Console.WriteLine("Agent created with Memory Search tool. Starting conversation...\n"); -// Conversation 2: Test if the agent remembers -Console.WriteLine("User: What's my name and what programming language do I prefer?"); -AgentResponse response2 = await agent.RunAsync("What's my name and what programming language do I prefer?"); -Console.WriteLine($"Agent: {response2.Messages.LastOrDefault()?.Text}\n"); + // The agent uses the memory search tool to recall stored information. + Console.WriteLine("User: What's my name and what programming language do I prefer?"); + AgentResponse response = await agent.RunAsync("What's my name and what programming language do I prefer?"); + Console.WriteLine($"Agent: {response.Messages.LastOrDefault()?.Text}\n"); -// Inspect memory search results if available in raw response items -// Note: Memory search tool call results appear as AgentResponseItem types -foreach (var message in response2.Messages) -{ - if (message.RawRepresentation is AgentResponseItem agentResponseItem && - agentResponseItem is MemorySearchToolCallResponseItem memorySearchResult) + // Inspect memory search results if available in raw response items. + foreach (var message in response.Messages) { - Console.WriteLine($"Memory Search Status: {memorySearchResult.Status}"); - Console.WriteLine($"Memory Search Results Count: {memorySearchResult.Results.Count}"); - - foreach (var result in memorySearchResult.Results) + if (message.RawRepresentation is MemorySearchToolCallResponseItem memorySearchResult) { - var memoryItem = result.MemoryItem; - Console.WriteLine($" - Memory ID: {memoryItem.MemoryId}"); - Console.WriteLine($" Scope: {memoryItem.Scope}"); - Console.WriteLine($" Content: {memoryItem.Content}"); - Console.WriteLine($" Updated: {memoryItem.UpdatedAt}"); + Console.WriteLine($"Memory Search Status: {memorySearchResult.Status}"); + Console.WriteLine($"Memory Search Results Count: {memorySearchResult.Results.Count}"); + + foreach (var result in memorySearchResult.Results) + { + var memoryItem = result.MemoryItem; + Console.WriteLine($" - Memory ID: {memoryItem.MemoryId}"); + Console.WriteLine($" Scope: {memoryItem.Scope}"); + Console.WriteLine($" Content: {memoryItem.Content}"); + Console.WriteLine($" Updated: {memoryItem.UpdatedAt}"); + } } } } +finally +{ + // Cleanup: Delete the agent and memory store. + Console.WriteLine("\nCleaning up..."); + await aiProjectClient.Agents.DeleteAgentAsync(agent.Name); + Console.WriteLine("Agent deleted."); + await aiProjectClient.MemoryStores.DeleteMemoryStoreAsync(memoryStoreName); + Console.WriteLine("Memory store deleted."); +} + +// Helpers — kept at the bottom so the main agent flow above stays clean. +async Task EnsureMemoryStoreAsync() +{ + Console.WriteLine($"Creating memory store '{memoryStoreName}'..."); + try + { + await aiProjectClient.MemoryStores.GetMemoryStoreAsync(memoryStoreName); + Console.WriteLine("Memory store already exists."); + } + catch (System.ClientModel.ClientResultException ex) when (ex.Status == 404) + { + MemoryStoreDefaultDefinition definition = new(deploymentName, embeddingModelName); + await aiProjectClient.MemoryStores.CreateMemoryStoreAsync(memoryStoreName, definition, "Sample memory store for Memory Search demo"); + Console.WriteLine("Memory store created."); + } + + Console.WriteLine("Storing memories from a prior conversation..."); + MemoryUpdateOptions memoryOptions = new(userScope) { UpdateDelay = 0 }; + memoryOptions.Items.Add(ResponseItem.CreateUserMessageItem("My name is Alice and I love programming in C#.")); + + MemoryUpdateResult updateResult = await aiProjectClient.MemoryStores.WaitForMemoriesUpdateAsync( + memoryStoreName: memoryStoreName, + options: memoryOptions, + pollingInterval: 500); -// Cleanup: Delete the agent (memory store persists and should be cleaned up separately if needed) -Console.WriteLine("\nCleaning up agent..."); -await aiProjectClient.Agents.DeleteAgentAsync(agent.Name); -Console.WriteLine("Agent deleted successfully."); + if (updateResult.Status == MemoryStoreUpdateStatus.Failed) + { + throw new InvalidOperationException($"Memory update failed: {updateResult.ErrorDetails}"); + } -// NOTE: Memory stores are long-lived resources and are NOT deleted with the agent. -// To delete a memory store, use the Azure Portal or Python SDK: -// await project_client.memory_stores.delete(memory_store.name) + Console.WriteLine($"Memory update completed (status: {updateResult.Status}).\n"); +} -// --- Agent Creation Options --- #pragma warning disable CS8321 // Local function is declared but never used // Option 1 - Using MemorySearchTool wrapped as MEAI AITool diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/README.md index 9e6d79d579..7a525ed358 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step22_MemorySearch/README.md @@ -15,18 +15,18 @@ This sample demonstrates how to use the Memory Search tool with AI agents. The M Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) - **A pre-created Memory Store** (see below) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). ### Creating a Memory Store Memory stores must be created before running this sample. The .NET SDK currently only supports **using** existing memory stores with agents. To create a memory store, use one of these methods: **Option 1: Azure Portal** -1. Navigate to your Azure AI Foundry project +1. Navigate to your Microsoft Foundry project 2. Go to the Memory section 3. Create a new memory store with your desired settings @@ -60,8 +60,8 @@ memory_store = await project_client.memory_stores.create( Set the following environment variables: ```powershell -$env:AZURE_FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" -$env:AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini $env:AZURE_AI_MEMORY_STORE_NAME="your-memory-store-name" # Required - name of pre-created memory store ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/Program.cs b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/Program.cs index d41771ef37..f619e8be3d 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/Program.cs +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/Program.cs @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. -// This sample demonstrates how to use a local MCP (Model Context Protocol) client with Azure Foundry Agents. +// This sample demonstrates how to use a local MCP (Model Context Protocol) client with Microsoft Foundry Agents. // The MCP tools are resolved locally by connecting directly to the MCP server via HTTP, // and then passed to the Foundry agent as client-side tools. // This sample uses the Microsoft Learn MCP endpoint to search documentation. @@ -34,7 +34,7 @@ // Wrap each MCP tool with a DelegatingAIFunction to log local invocations. List wrappedTools = mcpTools.Select(tool => (AITool)new LoggingMcpTool(tool)).ToList(); -// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents. +// Get a client to create/retrieve/delete server side agents with Microsoft Foundry Agents. // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. diff --git a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/README.md b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/README.md index 8651108987..4418e254bd 100644 --- a/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/FoundryAgents_Step23_LocalMCP/README.md @@ -1,6 +1,6 @@ -# Using Local MCP Client with Azure Foundry Agents +# Using Local MCP Client with Microsoft Foundry Agents -This sample demonstrates how to use a local MCP (Model Context Protocol) client with Azure Foundry Agents. Unlike the hosted MCP approach where Azure Foundry invokes the MCP server on the service side, this sample connects to the MCP server directly from the client via HTTP (Streamable HTTP transport) and passes the resolved tools to the agent. +This sample demonstrates how to use a local MCP (Model Context Protocol) client with Microsoft Foundry Agents. Unlike the hosted MCP approach where Microsoft Foundry invokes the MCP server on the service side, this sample connects to the MCP server directly from the client via HTTP (Streamable HTTP transport) and passes the resolved tools to the agent. ## What this sample demonstrates @@ -15,15 +15,15 @@ This sample demonstrates how to use a local MCP (Model Context Protocol) client Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and deployment configured +- Microsoft Foundry service endpoint and deployment configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryAgents/README.md b/dotnet/samples/02-agents/FoundryAgents/README.md index 426a8cdad5..881c87b1ba 100644 --- a/dotnet/samples/02-agents/FoundryAgents/README.md +++ b/dotnet/samples/02-agents/FoundryAgents/README.md @@ -1,19 +1,19 @@ # Getting started with Foundry Agents The getting started with Foundry Agents samples demonstrate the fundamental concepts and functionalities -of Azure Foundry Agents and can be used with Azure Foundry as the AI provider. +of Microsoft Foundry Agents and can be used with Microsoft Foundry as the AI provider. -These samples showcase how to work with agents managed through Azure Foundry, including agent creation, +These samples showcase how to work with agents managed through Microsoft Foundry, including agent creation, versioning, multi-turn conversations, and advanced features like code interpretation and computer use. ## Classic vs New Foundry Agents > [!NOTE] -> Recently, Azure Foundry introduced a new and improved experience for creating and managing AI agents, which is the target of these samples. +> Recently, Microsoft Foundry introduced a new and improved experience for creating and managing AI agents, which is the target of these samples. For more information about the previous classic agents and for what's new in Foundry Agents, see the [Foundry Agents migration documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/agents/how-to/migrate?view=foundry). -For a sample demonstrating how to use classic Foundry Agents, see the following: [Agent with Azure AI Persistent](../AgentProviders/Agent_With_AzureAIAgentsPersistent/README.md). +For a lightweight, code-first alternative that uses the Responses API directly (no server-side agent creation), see [Foundry Response Agents](../FoundryResponseAgents/README.md). ## Agent Versioning and Static Definitions @@ -31,12 +31,12 @@ The Agent Framework intentionally ignores unsupported runtime parameters rather Before you begin, ensure you have the following prerequisites: - .NET 10 SDK or later -- Azure Foundry service endpoint and project configured +- Microsoft Foundry service endpoint and project configured - Azure CLI installed and authenticated (for Azure credential authentication) -**Note**: These samples use Azure Foundry Agents. For more information, see [Azure AI Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/). +**Note**: These samples use Microsoft Foundry Agents. For more information, see [Microsoft Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/). -**Note**: These samples use Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). +**Note**: These samples use Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). ## Samples @@ -69,11 +69,11 @@ Before you begin, ensure you have the following prerequisites: ## Evaluation Samples -Evaluation is critical for building trustworthy and high-quality AI applications. The evaluation samples demonstrate how to assess agent safety, quality, and performance using Azure AI Foundry's evaluation capabilities. +Evaluation is critical for building trustworthy and high-quality AI applications. The evaluation samples demonstrate how to assess agent safety, quality, and performance using Microsoft Foundry's evaluation capabilities. |Sample|Description| |---|---| -|[Red Team Evaluation](./FoundryAgents_Evaluations_Step01_RedTeaming/)|This sample demonstrates how to use Azure AI Foundry's Red Teaming service to assess model safety against adversarial attacks| +|[Red Team Evaluation](./FoundryAgents_Evaluations_Step01_RedTeaming/)|This sample demonstrates how to use Microsoft Foundry's Red Teaming service to assess model safety against adversarial attacks| |[Self-Reflection with Groundedness](./FoundryAgents_Evaluations_Step02_SelfReflection/)|This sample demonstrates the self-reflection pattern where agents iteratively improve responses based on groundedness evaluation| For details on safety evaluation, see the [Red Team Evaluation README](./FoundryAgents_Evaluations_Step01_RedTeaming/README.md). @@ -89,7 +89,7 @@ cd FoundryAgents_Step01.2_Running Set the following environment variables: ```powershell -$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Azure Foundry resource endpoint +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" # Replace with your Microsoft Foundry resource endpoint $env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini ``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/FoundryAgentsRAPI_Step01_Basics.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/FoundryAgentsRAPI_Step01_Basics.csproj new file mode 100644 index 0000000000..5e73fd236a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/FoundryAgentsRAPI_Step01_Basics.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/Program.cs new file mode 100644 index 0000000000..0001b506fa --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/Program.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to create and run a basic agent using the Foundry Responses API directly, +// without creating a server-side agent definition. + +using Azure.Identity; +using Microsoft.Agents.AI.AzureAI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +// Create a FoundryAgentClient that uses the Responses API directly. +// No server-side agent is created — instructions and model are provided locally. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are good at telling jokes.", + name: "JokerAgent"); + +// Once you have the agent, you can invoke it like any other AIAgent. +Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.")); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/README.md new file mode 100644 index 0000000000..1e9687359e --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step01_Basics/README.md @@ -0,0 +1,37 @@ +# Creating and Running a Basic Agent with the Responses API + +This sample demonstrates how to create and run a basic AI agent using the `FoundryAgentClient`, which uses the Microsoft Foundry Responses API directly without creating server-side agent definitions. + +## What this sample demonstrates + +- Creating a `FoundryAgentClient` with instructions and a model +- Running a simple single-turn conversation +- No server-side agent creation or cleanup required + +## Prerequisites + +Before you begin, ensure you have the following prerequisites: + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (for Azure credential authentication) + +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +The `FoundryAgentClient` auto-discovers these environment variables — no endpoint or credential code is needed in the sample. + +## Run the sample + +Navigate to the FoundryAgents-RAPI sample directory and run: + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step01_Basics +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/FoundryAgentsRAPI_Step02_MultiturnConversation.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/FoundryAgentsRAPI_Step02_MultiturnConversation.csproj new file mode 100644 index 0000000000..5e73fd236a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/FoundryAgentsRAPI_Step02_MultiturnConversation.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/Program.cs new file mode 100644 index 0000000000..6c6216f5da --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/Program.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to create and use a multi-turn conversation agent using the Foundry Responses API directly. + +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +// Create a FoundryAgentClient that uses the Responses API directly. +// No server-side agent is created — instructions and model are provided locally. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are good at telling jokes.", + name: "JokerAgent"); + +// Invoke the agent with a multi-turn conversation, where the context is preserved in the session object. +AgentSession session = await agent.CreateSessionAsync(); + +Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session)); +Console.WriteLine(await agent.RunAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", session)); + +// Invoke the agent with a multi-turn conversation and streaming, where the context is preserved in the session object. +session = await agent.CreateSessionAsync(); +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a joke about a pirate.", session)) +{ + Console.Write(update); +} + +Console.WriteLine(); + +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", session)) +{ + Console.Write(update); +} + +Console.WriteLine(); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/README.md new file mode 100644 index 0000000000..cbfc996f0a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step02_MultiturnConversation/README.md @@ -0,0 +1,39 @@ +# Multi-turn Conversation with the Responses API + +This sample demonstrates how to implement multi-turn conversations using the `FoundryAgentClient`, where context is preserved across multiple agent runs using sessions. + +## What this sample demonstrates + +- Creating a `FoundryAgentClient` with instructions +- Using sessions to maintain conversation context across multiple runs +- Running multi-turn conversations with text output +- Running multi-turn conversations with streaming output +- No server-side agent creation or cleanup required + +## Prerequisites + +Before you begin, ensure you have the following prerequisites: + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (for Azure credential authentication) + +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +The `FoundryAgentClient` auto-discovers these environment variables — no endpoint or credential code is needed in the sample. + +## Run the sample + +Navigate to the FoundryAgents-RAPI sample directory and run: + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step02_MultiturnConversation +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/FoundryAgentsRAPI_Step03_UsingFunctionTools.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/FoundryAgentsRAPI_Step03_UsingFunctionTools.csproj new file mode 100644 index 0000000000..5e73fd236a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/FoundryAgentsRAPI_Step03_UsingFunctionTools.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/Program.cs new file mode 100644 index 0000000000..b0d3fd989c --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/Program.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample demonstrates how to use function tools with the Foundry Responses API directly. + +using System.ComponentModel; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +[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."; + +// Define the function tool. +AITool tool = AIFunctionFactory.Create(GetWeather); + +// Create a FoundryAgentClient that uses the Responses API directly with function tools. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are a helpful assistant that can get weather information.", + name: "WeatherAssistant", + tools: [tool]); + +// Non-streaming agent interaction with function tools. +AgentSession session = await agent.CreateSessionAsync(); +Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?", session)); + +// Streaming agent interaction with function tools. +session = await agent.CreateSessionAsync(); +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("What is the weather like in Amsterdam?", session)) +{ + Console.Write(update); +} + +Console.WriteLine(); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/README.md new file mode 100644 index 0000000000..9116e1db68 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step03_UsingFunctionTools/README.md @@ -0,0 +1,39 @@ +# Using Function Tools with the Responses API + +This sample demonstrates how to use function tools with the `FoundryAgentClient`, allowing the agent to call custom functions to retrieve information. + +## What this sample demonstrates + +- Creating function tools using `AIFunctionFactory` +- Passing function tools to a `FoundryAgentClient` +- Running agents with function tools (text output) +- Running agents with function tools (streaming output) +- No server-side agent creation or cleanup required + +## Prerequisites + +Before you begin, ensure you have the following prerequisites: + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (for Azure credential authentication) + +**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Microsoft Foundry resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +The `FoundryAgentClient` auto-discovers these environment variables — no endpoint or credential code is needed in the sample. + +## Run the sample + +Navigate to the FoundryAgents-RAPI sample directory and run: + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step03_UsingFunctionTools +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals.csproj new file mode 100644 index 0000000000..5e73fd236a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/Program.cs new file mode 100644 index 0000000000..ab0ae970ad --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/Program.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample demonstrates how to use an agent with function tools that require a human in the loop for approvals. + +using System.ComponentModel; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +[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."; + +ApprovalRequiredAIFunction approvalTool = new(AIFunctionFactory.Create(GetWeather, name: nameof(GetWeather))); + +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are a helpful assistant that can get weather information.", + name: "WeatherAssistant", + tools: [approvalTool]); + +// Call the agent with approval-required function tools. +AgentSession session = await agent.CreateSessionAsync(); +AgentResponse response = await agent.RunAsync("What is the weather like in Amsterdam?", session); + +// Check if there are any approval requests. +List approvalRequests = response.Messages.SelectMany(m => m.Contents).OfType().ToList(); + +while (approvalRequests.Count > 0) +{ + // Ask the user to approve each function call request. + List userInputMessages = approvalRequests + .ConvertAll(functionApprovalRequest => + { + Console.WriteLine($"The agent would like to invoke the following function, please reply Y to approve: Name {functionApprovalRequest.FunctionCall.Name}"); + bool approved = Console.ReadLine()?.Equals("Y", StringComparison.OrdinalIgnoreCase) ?? false; + return new ChatMessage(ChatRole.User, [functionApprovalRequest.CreateResponse(approved)]); + }); + + response = await agent.RunAsync(userInputMessages, session); + approvalRequests = response.Messages.SelectMany(m => m.Contents).OfType().ToList(); +} + +Console.WriteLine($"\nAgent: {response}"); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/README.md new file mode 100644 index 0000000000..4484cf0f01 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/README.md @@ -0,0 +1,30 @@ +# Using Function Tools with Approvals via the Responses API + +This sample demonstrates how to use function tools that require human-in-the-loop approval before execution. + +## What this sample demonstrates + +- Creating function tools that require approval using `ApprovalRequiredAIFunction` +- Handling approval requests from the agent +- Passing approval responses back to the agent +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/FoundryAgentsRAPI_Step05_StructuredOutput.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/FoundryAgentsRAPI_Step05_StructuredOutput.csproj new file mode 100644 index 0000000000..5e73fd236a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/FoundryAgentsRAPI_Step05_StructuredOutput.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/Program.cs new file mode 100644 index 0000000000..a135f7db4d --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/Program.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to configure an agent to produce structured output using the Responses API directly. + +using System.ComponentModel; +using System.Text.Json; +using System.Text.Json.Serialization; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using SampleApp; + +#pragma warning disable CA5399 + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + options: new ChatClientAgentOptions + { + Name = "StructuredOutputAssistant", + ChatOptions = new() + { + ModelId = deploymentName, + Instructions = "You are a helpful assistant that extracts structured information about people.", + ResponseFormat = Microsoft.Extensions.AI.ChatResponseFormat.ForJsonSchema() + } + }); + +// Set PersonInfo as the type parameter of RunAsync method to specify the expected structured output. +AgentResponse response = await agent.RunAsync("Please provide information about John Smith, who is a 35-year-old software engineer."); + +// Access the structured output via the Result property of the agent response. +Console.WriteLine("Assistant Output:"); +Console.WriteLine($"Name: {response.Result.Name}"); +Console.WriteLine($"Age: {response.Result.Age}"); +Console.WriteLine($"Occupation: {response.Result.Occupation}"); + +// Invoke the agent with streaming support, then deserialize the assembled response. +IAsyncEnumerable updates = agent.RunStreamingAsync("Please provide information about Jane Doe, who is a 28-year-old data scientist."); + +PersonInfo personInfo = JsonSerializer.Deserialize((await updates.ToAgentResponseAsync()).Text, JsonSerializerOptions.Web) + ?? throw new InvalidOperationException("Failed to deserialize the streamed response into PersonInfo."); + +Console.WriteLine("\nStreaming Assistant Output:"); +Console.WriteLine($"Name: {personInfo.Name}"); +Console.WriteLine($"Age: {personInfo.Age}"); +Console.WriteLine($"Occupation: {personInfo.Occupation}"); + +namespace SampleApp +{ + /// + /// Represents information about a person. + /// + [Description("Information about a person including their name, age, and occupation")] + public class PersonInfo + { + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("age")] + public int? Age { get; set; } + + [JsonPropertyName("occupation")] + public string? Occupation { get; set; } + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/README.md new file mode 100644 index 0000000000..64058fc5f9 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step05_StructuredOutput/README.md @@ -0,0 +1,29 @@ +# Structured Output with the Responses API + +This sample demonstrates how to configure an agent to produce structured output using JSON schema. + +## What this sample demonstrates + +- Using `RunAsync()` to get typed structured output from the agent +- Deserializing streamed responses into structured types +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step05_StructuredOutput +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/FoundryAgentsRAPI_Step06_PersistedConversations.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/FoundryAgentsRAPI_Step06_PersistedConversations.csproj new file mode 100644 index 0000000000..5e73fd236a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/FoundryAgentsRAPI_Step06_PersistedConversations.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/Program.cs new file mode 100644 index 0000000000..89384b8166 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/Program.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to persist and resume conversations using the Responses API directly. + +using System.Text.Json; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are good at telling jokes.", + name: "JokerAgent"); + +// Start a new session for the agent conversation. +AgentSession session = await agent.CreateSessionAsync(); + +// Run the agent with a new session. +Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session)); + +// Serialize the session state to a JsonElement, so it can be stored for later use. +JsonElement serializedSession = await agent.SerializeSessionAsync(session); + +// Save the serialized session to a temporary file (for demonstration purposes). +string tempFilePath = Path.GetTempFileName(); +await File.WriteAllTextAsync(tempFilePath, JsonSerializer.Serialize(serializedSession)); + +// Load the serialized session from the temporary file (for demonstration purposes). +JsonElement reloadedSerializedSession = JsonElement.Parse(await File.ReadAllTextAsync(tempFilePath))!; + +// Deserialize the session state after loading from storage. +AgentSession resumedSession = await agent.DeserializeSessionAsync(reloadedSerializedSession); + +// Run the agent again with the resumed session. +Console.WriteLine(await agent.RunAsync("Now tell the same joke in the voice of a pirate, and add some emojis to the joke.", resumedSession)); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/README.md new file mode 100644 index 0000000000..3bf0f243f0 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step06_PersistedConversations/README.md @@ -0,0 +1,30 @@ +# Persisted Conversations with the Responses API + +This sample demonstrates how to persist and resume agent conversations using session serialization. + +## What this sample demonstrates + +- Serializing agent sessions to JSON for persistence +- Saving and loading sessions from disk +- Resuming conversations with preserved context +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step06_PersistedConversations +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/FoundryAgentsRAPI_Step07_Observability.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/FoundryAgentsRAPI_Step07_Observability.csproj new file mode 100644 index 0000000000..5350f8236d --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/FoundryAgentsRAPI_Step07_Observability.csproj @@ -0,0 +1,21 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/Program.cs new file mode 100644 index 0000000000..0b26f14d71 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/Program.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to add OpenTelemetry observability to an agent using the Responses API directly. + +using Azure.Identity; +using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using OpenTelemetry; +using OpenTelemetry.Trace; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; +string? applicationInsightsConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING"); + +// Create TracerProvider with console exporter. +string sourceName = Guid.NewGuid().ToString("N"); +TracerProviderBuilder tracerProviderBuilder = Sdk.CreateTracerProviderBuilder() + .AddSource(sourceName) + .AddConsoleExporter(); +if (!string.IsNullOrWhiteSpace(applicationInsightsConnectionString)) +{ + tracerProviderBuilder.AddAzureMonitorTraceExporter(options => options.ConnectionString = applicationInsightsConnectionString); +} +using var tracerProvider = tracerProviderBuilder.Build(); + +// Create a FoundryAgentClient using environment variable auto-discovery. +// AZURE_AI_PROJECT_ENDPOINT - The Microsoft Foundry project endpoint URL. +// AZURE_AI_MODEL_DEPLOYMENT_NAME - The model deployment name to use. +AIAgent agent = new FoundryResponsesAgent( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are good at telling jokes.", + name: "JokerAgent") + .AsBuilder() + .UseOpenTelemetry(sourceName: sourceName) + .Build(); + +// Invoke the agent and output the text result. +AgentSession session = await agent.CreateSessionAsync(); +Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session)); + +// Invoke the agent with streaming support. +session = await agent.CreateSessionAsync(); +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a joke about a pirate.", session)) +{ + Console.Write(update); +} + +Console.WriteLine(); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/README.md new file mode 100644 index 0000000000..b69fff87f7 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step07_Observability/README.md @@ -0,0 +1,31 @@ +# Observability with the Responses API + +This sample demonstrates how to add OpenTelemetry observability to an agent using console and Azure Monitor exporters. + +## What this sample demonstrates + +- Configuring OpenTelemetry tracing with console exporter +- Optional Azure Application Insights integration +- Using `.AsBuilder().UseOpenTelemetry()` to add telemetry to the agent +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +$env:APPLICATIONINSIGHTS_CONNECTION_STRING="..." # Optional +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step07_Observability +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/FoundryAgentsRAPI_Step08_DependencyInjection.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/FoundryAgentsRAPI_Step08_DependencyInjection.csproj new file mode 100644 index 0000000000..ffa39538d5 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/FoundryAgentsRAPI_Step08_DependencyInjection.csproj @@ -0,0 +1,21 @@ + + + + Exe + net10.0 + + enable + enable + + $(NoWarn);CA1812 + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/Program.cs new file mode 100644 index 0000000000..82ed0312ba --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/Program.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use dependency injection to register a FoundryAgentClient and use it from a hosted service. + +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are good at telling jokes.", + name: "JokerAgent"); + +// Create a host builder that we will register services with and then run. +HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); + +// Add the AI agent to the service collection. +builder.Services.AddSingleton(agent); + +// Add a sample service that will use the agent to respond to user input. +builder.Services.AddHostedService(); + +// Build and run the host. +using IHost host = builder.Build(); +await host.RunAsync().ConfigureAwait(false); + +/// +/// A sample service that uses an AI agent to respond to user input. +/// +internal sealed class SampleService(AIAgent agent, IHostApplicationLifetime appLifetime) : IHostedService +{ + private AgentSession? _session; + + public async Task StartAsync(CancellationToken cancellationToken) + { + this._session = await agent.CreateSessionAsync(cancellationToken); + _ = this.RunAsync(appLifetime.ApplicationStopping); + } + + public async Task RunAsync(CancellationToken cancellationToken) + { + await Task.Delay(100, cancellationToken); + + while (!cancellationToken.IsCancellationRequested) + { + Console.WriteLine("\nAgent: Ask me to tell you a joke about a specific topic. To exit just press Ctrl+C or enter without any input.\n"); + Console.Write("> "); + string? input = Console.ReadLine(); + + if (string.IsNullOrWhiteSpace(input)) + { + appLifetime.StopApplication(); + break; + } + + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, this._session, cancellationToken: cancellationToken)) + { + Console.Write(update); + } + + Console.WriteLine(); + } + } + + public Task StopAsync(CancellationToken cancellationToken) + { + Console.WriteLine("\nShutting down..."); + return Task.CompletedTask; + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/README.md new file mode 100644 index 0000000000..691d2e3b11 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step08_DependencyInjection/README.md @@ -0,0 +1,30 @@ +# Dependency Injection with the Responses API + +This sample demonstrates how to register a `FoundryAgentClient` in a dependency injection container and use it from a hosted service. + +## What this sample demonstrates + +- Registering `FoundryAgentClient` as an `AIAgent` in the service collection +- Using the agent from a `IHostedService` with an interactive chat loop +- Streaming responses in a hosted service context +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step08_DependencyInjection +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools.csproj new file mode 100644 index 0000000000..a69c81f08c --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools.csproj @@ -0,0 +1,20 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/Program.cs new file mode 100644 index 0000000000..01a75948d5 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/Program.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use MCP client tools with a FoundryAgentClient using the Responses API directly. + +using Azure.Identity; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; +using ModelContextProtocol.Client; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +Console.WriteLine("Starting MCP Stdio for @modelcontextprotocol/server-github ... "); + +// Create an MCPClient for the GitHub server +await using var mcpClient = await McpClient.CreateAsync(new StdioClientTransport(new() +{ + Name = "MCPServer", + Command = "npx", + Arguments = ["-y", "--verbose", "@modelcontextprotocol/server-github"], +})); + +// Retrieve the list of tools available on the GitHub server +IList mcpTools = await mcpClient.ListToolsAsync(); + +// Create a FoundryAgentClient that uses the Responses API directly with MCP tools. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You answer questions related to GitHub repositories only.", + name: "AgentWithMCP", + tools: [.. mcpTools.Cast()]); + +string prompt = "Summarize the last four commits to the microsoft/semantic-kernel repository?"; + +Console.WriteLine($"Invoking agent '{agent.Name}' with prompt: {prompt} ..."); + +// Invoke the agent and output the text result. +Console.WriteLine(await agent.RunAsync(prompt)); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/README.md new file mode 100644 index 0000000000..714df58f74 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/README.md @@ -0,0 +1,29 @@ +# Using MCP Client as Tools with the Responses API + +This sample shows how to use MCP (Model Context Protocol) client tools with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Connecting to an MCP server (GitHub) via stdio transport +- Retrieving MCP tools and passing them to a `FoundryAgentClient` +- Using MCP tools for agent interactions without server-side agent creation + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) +- Node.js installed (for npx/MCP server) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/FoundryAgentsRAPI_Step10_UsingImages.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/FoundryAgentsRAPI_Step10_UsingImages.csproj new file mode 100644 index 0000000000..91ad19c6ab --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/FoundryAgentsRAPI_Step10_UsingImages.csproj @@ -0,0 +1,21 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + PreserveNewest + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/Program.cs new file mode 100644 index 0000000000..9fc6faa28b --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/Program.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use image multi-modality with an agent using the Responses API directly. + +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o"; + +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are a helpful agent that can analyze images.", + name: "VisionAgent"); + +ChatMessage message = new(ChatRole.User, [ + new TextContent("What do you see in this image?"), + await DataContent.LoadFromAsync("assets/walkway.jpg"), +]); + +AgentSession session = await agent.CreateSessionAsync(); + +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(message, session)) +{ + Console.Write(update); +} + +Console.WriteLine(); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/README.md new file mode 100644 index 0000000000..ca3d08dd5f --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/README.md @@ -0,0 +1,30 @@ +# Using Images with the Responses API + +This sample demonstrates how to use image multi-modality with an agent. + +## What this sample demonstrates + +- Loading images using `DataContent.LoadFromAsync` +- Sending images alongside text to the agent +- Streaming the agent's image analysis response +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and a vision-capable model deployment (e.g., `gpt-4o`) +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o" +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step10_UsingImages +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/assets/walkway.jpg b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/assets/walkway.jpg new file mode 100644 index 0000000000..13ef1e1840 Binary files /dev/null and b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step10_UsingImages/assets/walkway.jpg differ diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/FoundryAgentsRAPI_Step11_AsFunctionTool.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/FoundryAgentsRAPI_Step11_AsFunctionTool.csproj new file mode 100644 index 0000000000..5e73fd236a --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/FoundryAgentsRAPI_Step11_AsFunctionTool.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/Program.cs new file mode 100644 index 0000000000..6138ee46dc --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/Program.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use one agent as a function tool for another agent using the Responses API directly. + +using System.ComponentModel; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +[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."; + +AITool weatherTool = AIFunctionFactory.Create(GetWeather); +FoundryResponsesAgent weatherAgent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You answer questions about the weather.", + name: "WeatherAgent", + tools: [weatherTool]); + +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are a helpful assistant who responds in French.", + name: "MainAgent", + tools: [weatherAgent.AsAIFunction()]); + +// Invoke the agent and output the text result. +AgentSession session = await agent.CreateSessionAsync(); +Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?", session)); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/README.md new file mode 100644 index 0000000000..dd4e80edf5 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step11_AsFunctionTool/README.md @@ -0,0 +1,30 @@ +# Agent as a Function Tool with the Responses API + +This sample demonstrates how to use one agent as a function tool for another agent. + +## What this sample demonstrates + +- Creating a specialized agent (weather) with function tools +- Exposing an agent as a function tool using `.AsAIFunction()` +- Composing agents where one agent delegates to another +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step11_AsFunctionTool +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/FoundryAgentsRAPI_Step12_Middleware.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/FoundryAgentsRAPI_Step12_Middleware.csproj new file mode 100644 index 0000000000..811a1eacb6 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/FoundryAgentsRAPI_Step12_Middleware.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/Program.cs new file mode 100644 index 0000000000..25f7dc8627 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/Program.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows multiple middleware layers working together with the Responses API: +// agent run (PII filtering and guardrails), +// function invocation (logging and result overrides), and human-in-the-loop +// approval workflows for sensitive function calls. + +using System.ComponentModel; +using System.Text.RegularExpressions; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +[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."; + +[Description("The current datetime offset.")] +static string GetDateTime() + => DateTimeOffset.Now.ToString(); + +AITool dateTimeTool = AIFunctionFactory.Create(GetDateTime, name: nameof(GetDateTime)); +AITool getWeatherTool = AIFunctionFactory.Create(GetWeather, name: nameof(GetWeather)); + +FoundryResponsesAgent originalAgent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are an AI assistant that helps people find information.", + name: "InformationAssistant", + tools: [getWeatherTool, dateTimeTool]); + +// Adding middleware to the agent level +AIAgent middlewareEnabledAgent = originalAgent + .AsBuilder() + .Use(FunctionCallMiddleware) + .Use(FunctionCallOverrideWeather) + .Use(PIIMiddleware, null) + .Use(GuardrailMiddleware, null) + .Build(); + +AgentSession session = await middlewareEnabledAgent.CreateSessionAsync(); + +Console.WriteLine("\n\n=== Example 1: Wording Guardrail ==="); +AgentResponse guardRailedResponse = await middlewareEnabledAgent.RunAsync("Tell me something harmful."); +Console.WriteLine($"Guard railed response: {guardRailedResponse}"); + +Console.WriteLine("\n\n=== Example 2: PII detection ==="); +AgentResponse piiResponse = await middlewareEnabledAgent.RunAsync("My name is John Doe, call me at 123-456-7890 or email me at john@something.com"); +Console.WriteLine($"Pii filtered response: {piiResponse}"); + +Console.WriteLine("\n\n=== Example 3: Agent function middleware ==="); +AgentResponse functionCallResponse = await middlewareEnabledAgent.RunAsync("What's the current time and the weather in Seattle?", session); +Console.WriteLine($"Function calling response: {functionCallResponse}"); + +// Special per-request middleware agent. +Console.WriteLine("\n\n=== Example 4: Middleware with human in the loop function approval ==="); + +FoundryResponsesAgent humanInTheLoopAgent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: "You are a Human in the loop testing AI assistant that helps people find information.", + name: "HumanInTheLoopAgent", + tools: [new ApprovalRequiredAIFunction(AIFunctionFactory.Create(GetWeather, name: nameof(GetWeather)))]); + +AgentResponse response = await humanInTheLoopAgent + .AsBuilder() + .Use(ConsolePromptingApprovalMiddleware, null) + .Build() + .RunAsync("What's the current time and the weather in Seattle?"); + +Console.WriteLine($"HumanInTheLoopAgent agent middleware response: {response}"); + +// Function invocation middleware that logs before and after function calls. +async ValueTask FunctionCallMiddleware(AIAgent agent, FunctionInvocationContext context, Func> next, CancellationToken cancellationToken) +{ + Console.WriteLine($"Function Name: {context!.Function.Name} - Middleware 1 Pre-Invoke"); + var result = await next(context, cancellationToken); + Console.WriteLine($"Function Name: {context!.Function.Name} - Middleware 1 Post-Invoke"); + + return result; +} + +// Function invocation middleware that overrides the result of the GetWeather function. +async ValueTask FunctionCallOverrideWeather(AIAgent agent, FunctionInvocationContext context, Func> next, CancellationToken cancellationToken) +{ + Console.WriteLine($"Function Name: {context!.Function.Name} - Middleware 2 Pre-Invoke"); + + var result = await next(context, cancellationToken); + + if (context.Function.Name == nameof(GetWeather)) + { + result = "The weather is sunny with a high of 25°C."; + } + Console.WriteLine($"Function Name: {context!.Function.Name} - Middleware 2 Post-Invoke"); + return result; +} + +// This middleware redacts PII information from input and output messages. +async Task PIIMiddleware(IEnumerable messages, AgentSession? session, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +{ + var filteredMessages = FilterMessages(messages); + Console.WriteLine("Pii Middleware - Filtered Messages Pre-Run"); + + var agentResponse = await innerAgent.RunAsync(filteredMessages, session, options, cancellationToken).ConfigureAwait(false); + + agentResponse.Messages = FilterMessages(agentResponse.Messages); + + Console.WriteLine("Pii Middleware - Filtered Messages Post-Run"); + + return agentResponse; + + static IList FilterMessages(IEnumerable messages) + { + return messages.Select(m => new ChatMessage(m.Role, FilterPii(m.Text))).ToList(); + } + + static string FilterPii(string content) + { + Regex[] piiPatterns = [ + new(@"\b\d{3}-\d{3}-\d{4}\b", RegexOptions.Compiled), + new(@"\b[\w\.-]+@[\w\.-]+\.\w+\b", RegexOptions.Compiled), + new(@"\b[A-Z][a-z]+\s[A-Z][a-z]+\b", RegexOptions.Compiled) + ]; + + foreach (var pattern in piiPatterns) + { + content = pattern.Replace(content, "[REDACTED: PII]"); + } + + return content; + } +} + +// This middleware enforces guardrails by redacting certain keywords from input and output messages. +async Task GuardrailMiddleware(IEnumerable messages, AgentSession? session, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +{ + var filteredMessages = FilterMessages(messages); + + Console.WriteLine("Guardrail Middleware - Filtered messages Pre-Run"); + + var agentResponse = await innerAgent.RunAsync(filteredMessages, session, options, cancellationToken); + + agentResponse.Messages = FilterMessages(agentResponse.Messages); + + Console.WriteLine("Guardrail Middleware - Filtered messages Post-Run"); + + return agentResponse; + + List FilterMessages(IEnumerable messages) + { + return messages.Select(m => new ChatMessage(m.Role, FilterContent(m.Text))).ToList(); + } + + static string FilterContent(string content) + { + foreach (var keyword in new[] { "harmful", "illegal", "violence" }) + { + if (content.Contains(keyword, StringComparison.OrdinalIgnoreCase)) + { + return "[REDACTED: Forbidden content]"; + } + } + + return content; + } +} + +// This middleware handles Human in the loop console interaction for any user approval required during function calling. +async Task ConsolePromptingApprovalMiddleware(IEnumerable messages, AgentSession? session, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +{ + AgentResponse agentResponse = await innerAgent.RunAsync(messages, session, options, cancellationToken); + + List approvalRequests = agentResponse.Messages.SelectMany(m => m.Contents).OfType().ToList(); + + while (approvalRequests.Count > 0) + { + agentResponse.Messages = approvalRequests + .ConvertAll(functionApprovalRequest => + { + Console.WriteLine($"The agent would like to invoke the following function, please reply Y to approve: Name {functionApprovalRequest.FunctionCall.Name}"); + bool approved = Console.ReadLine()?.Equals("Y", StringComparison.OrdinalIgnoreCase) ?? false; + return new ChatMessage(ChatRole.User, [functionApprovalRequest.CreateResponse(approved)]); + }); + + agentResponse = await innerAgent.RunAsync(agentResponse.Messages, session, options, cancellationToken); + + approvalRequests = agentResponse.Messages.SelectMany(m => m.Contents).OfType().ToList(); + } + + return agentResponse; +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/README.md new file mode 100644 index 0000000000..2312b30859 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step12_Middleware/README.md @@ -0,0 +1,31 @@ +# Middleware with the Responses API + +This sample demonstrates multiple middleware layers working together: PII filtering, guardrails, function invocation logging, and human-in-the-loop approval. + +## What this sample demonstrates + +- Agent-level run middleware (PII filtering, guardrail enforcement) +- Function-level middleware (logging, result overrides) +- Human-in-the-loop approval workflows for sensitive function calls +- Using `.AsBuilder().Use()` to compose middleware +- No server-side agent creation or cleanup required + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +cd dotnet/samples/02-agents/FoundryAgents-RAPI +dotnet run --project .\FoundryAgentsRAPI_Step12_Middleware +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/FoundryAgentsRAPI_Step13_Plugins.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/FoundryAgentsRAPI_Step13_Plugins.csproj new file mode 100644 index 0000000000..489a070620 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/FoundryAgentsRAPI_Step13_Plugins.csproj @@ -0,0 +1,21 @@ + + + + Exe + net10.0 + + enable + enable + $(NoWarn);CA1812 + + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/Program.cs new file mode 100644 index 0000000000..28355c58dd --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/Program.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use plugins with a FoundryAgentClient using the Responses API directly. +// Plugin classes can depend on other services that need to be injected. + +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.DependencyInjection; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +const string AssistantInstructions = "You are a helpful assistant that helps people find information."; +const string AssistantName = "PluginAssistant"; + +// Create a service collection to hold the agent plugin and its dependencies. +ServiceCollection services = new(); +services.AddSingleton(); +services.AddSingleton(); +services.AddSingleton(); // The plugin depends on WeatherProvider and CurrentTimeProvider registered above. + +IServiceProvider serviceProvider = services.BuildServiceProvider(); + +// Create a FoundryAgentClient with the options-based constructor to pass services. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + clientOptions: null, + options: new ChatClientAgentOptions + { + Name = AssistantName, + ChatOptions = new() { ModelId = deploymentName, Instructions = AssistantInstructions, Tools = serviceProvider.GetRequiredService().AsAITools().ToList() } + }, + services: serviceProvider); + +// Invoke the agent and output the text result. +AgentSession session = await agent.CreateSessionAsync(); +Console.WriteLine(await agent.RunAsync("Tell me current time and weather in Seattle.", session)); + +/// +/// The agent plugin that provides weather and current time information. +/// +/// The weather provider to get weather information. +internal sealed class AgentPlugin(WeatherProvider weatherProvider) +{ + /// + /// Gets the weather information for the specified location. + /// + /// The location to get the weather for. + /// The weather information for the specified location. + public string GetWeather(string location) + { + return weatherProvider.GetWeather(location); + } + + /// + /// Gets the current date and time for the specified location. + /// + /// The service provider to resolve the . + /// The location to get the current time for. + /// The current date and time as a . + public DateTimeOffset GetCurrentTime(IServiceProvider sp, string location) + { + CurrentTimeProvider currentTimeProvider = sp.GetRequiredService(); + return currentTimeProvider.GetCurrentTime(location); + } + + /// + /// Returns the functions provided by this plugin. + /// + /// The functions provided by this plugin. + public IEnumerable AsAITools() + { + yield return AIFunctionFactory.Create(this.GetWeather); + yield return AIFunctionFactory.Create(this.GetCurrentTime); + } +} + +/// +/// The weather provider that returns weather information. +/// +internal sealed class WeatherProvider +{ + /// + /// Gets the weather information for the specified location. + /// + /// The location to get the weather for. + /// The weather information for the specified location. + public string GetWeather(string location) + { + return $"The weather in {location} is cloudy with a high of 15°C."; + } +} + +/// +/// Provides the current date and time. +/// +internal sealed class CurrentTimeProvider +{ + /// + /// Gets the current date and time. + /// + /// The location to get the current time for (not used in this implementation). + /// The current date and time as a . + public DateTimeOffset GetCurrentTime(string location) + { + return DateTimeOffset.Now; + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/README.md new file mode 100644 index 0000000000..161d4dc7af --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step13_Plugins/README.md @@ -0,0 +1,29 @@ +# Using Plugins with the Responses API + +This sample shows how to use plugins with a `FoundryAgentClient` using the Responses API directly, with dependency injection for plugin services. + +## What this sample demonstrates + +- Creating plugin classes with injected dependencies +- Registering services and building a service provider +- Passing `services` to the `FoundryAgentClient` via the options-based constructor +- Using `AIFunctionFactory` to expose plugin methods as AI tools + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/FoundryAgentsRAPI_Step14_CodeInterpreter.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/FoundryAgentsRAPI_Step14_CodeInterpreter.csproj new file mode 100644 index 0000000000..c6c12051e1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/FoundryAgentsRAPI_Step14_CodeInterpreter.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/Program.cs new file mode 100644 index 0000000000..3a5adadcf4 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/Program.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use Code Interpreter Tool with a FoundryAgentClient using the Responses API directly. + +using System.Text; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; +using OpenAI.Assistants; +using OpenAI.Responses; + +string endpoint= Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +const string AgentInstructions = "You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question."; +const string AgentName = "CoderAgent-RAPI"; + +// Create a FoundryAgentClient with HostedCodeInterpreterTool using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: AgentName, + tools: [new HostedCodeInterpreterTool() { Inputs = [] }]); + +AgentResponse response = await agent.RunAsync("I need to solve the equation sin(x) + x^2 = 42"); + +// Get the CodeInterpreterToolCallContent +CodeInterpreterToolCallContent? toolCallContent = response.Messages.SelectMany(m => m.Contents).OfType().FirstOrDefault(); +if (toolCallContent?.Inputs is not null) +{ + DataContent? codeInput = toolCallContent.Inputs.OfType().FirstOrDefault(); + if (codeInput?.HasTopLevelMediaType("text") ?? false) + { + Console.WriteLine($"Code Input: {Encoding.UTF8.GetString(codeInput.Data.ToArray()) ?? "Not available"}"); + } +} + +// Get the CodeInterpreterToolResultContent +CodeInterpreterToolResultContent? toolResultContent = response.Messages.SelectMany(m => m.Contents).OfType().FirstOrDefault(); +if (toolResultContent?.Outputs is not null && toolResultContent.Outputs.OfType().FirstOrDefault() is { } resultOutput) +{ + Console.WriteLine($"Code Tool Result: {resultOutput.Text}"); +} + +// Getting any annotations generated by the tool +foreach (AIAnnotation annotation in response.Messages.SelectMany(m => m.Contents).SelectMany(C => C.Annotations ?? [])) +{ + if (annotation.RawRepresentation is TextAnnotationUpdate citationAnnotation) + { + Console.WriteLine($$""" + File Id: {{citationAnnotation.OutputFileId}} + Text to Replace: {{citationAnnotation.TextToReplace}} + Filename: {{Path.GetFileName(citationAnnotation.TextToReplace)}} + """); + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/README.md new file mode 100644 index 0000000000..a2ceff44ea --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step14_CodeInterpreter/README.md @@ -0,0 +1,28 @@ +# Code Interpreter with the Responses API + +This sample shows how to use the Code Interpreter tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Using `HostedCodeInterpreterTool` with `FoundryAgentClient` +- Extracting code input and output from agent responses +- Handling code interpreter annotations and file citations + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_browser_search.png b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_browser_search.png new file mode 100644 index 0000000000..5984b95cb3 Binary files /dev/null and b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_browser_search.png differ diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_search_results.png b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_search_results.png new file mode 100644 index 0000000000..ed3ab3d8d4 Binary files /dev/null and b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_search_results.png differ diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_search_typed.png b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_search_typed.png new file mode 100644 index 0000000000..04d76e2075 Binary files /dev/null and b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Assets/cua_search_typed.png differ diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/ComputerUseUtil.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/ComputerUseUtil.cs new file mode 100644 index 0000000000..1ee421b465 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/ComputerUseUtil.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft. All rights reserved. + +using OpenAI.Responses; + +namespace Demo.ComputerUse; + +/// +/// Enum for tracking the state of the simulated web search flow. +/// +internal enum SearchState +{ + Initial, // Browser search page + Typed, // Text entered in search box + PressedEnter // Enter key pressed, transitioning to results +} + +internal static class ComputerUseUtil +{ + /// + /// Load and convert screenshot images to base64 data URLs. + /// + internal static Dictionary LoadScreenshotAssets() + { + string baseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets"); + + ReadOnlySpan<(string key, string fileName)> screenshotFiles = + [ + ("browser_search", "cua_browser_search.png"), + ("search_typed", "cua_search_typed.png"), + ("search_results", "cua_search_results.png") + ]; + + Dictionary screenshots = []; + foreach (var (key, fileName) in screenshotFiles) + { + string fullPath = Path.GetFullPath(Path.Combine(baseDir, fileName)); + screenshots[key] = File.ReadAllBytes(fullPath); + } + + return screenshots; + } + + /// + /// Process a computer action and simulate its execution. + /// + internal static (SearchState CurrentState, byte[] ImageBytes) HandleComputerActionAndTakeScreenshot( + ComputerCallAction action, + SearchState currentState, + Dictionary screenshots) + { + Console.WriteLine($"Simulating the execution of computer action: {action.Kind}"); + + SearchState newState = DetermineNextState(action, currentState); + string imageKey = GetImageKey(newState); + + return (newState, screenshots[imageKey]); + } + + private static SearchState DetermineNextState(ComputerCallAction action, SearchState currentState) + { + string actionType = action.Kind.ToString(); + + if (actionType.Equals("type", StringComparison.OrdinalIgnoreCase) && action.TypeText is not null) + { + return SearchState.Typed; + } + + if (IsEnterKeyAction(action, actionType)) + { + Console.WriteLine(" -> Detected ENTER key press"); + return SearchState.PressedEnter; + } + + if (actionType.Equals("click", StringComparison.OrdinalIgnoreCase) && currentState == SearchState.Typed) + { + Console.WriteLine(" -> Detected click after typing"); + return SearchState.PressedEnter; + } + + return currentState; + } + + private static bool IsEnterKeyAction(ComputerCallAction action, string actionType) + { + return (actionType.Equals("key", StringComparison.OrdinalIgnoreCase) || + actionType.Equals("keypress", StringComparison.OrdinalIgnoreCase)) && + action.KeyPressKeyCodes is not null && + (action.KeyPressKeyCodes.Contains("Return", StringComparer.OrdinalIgnoreCase) || + action.KeyPressKeyCodes.Contains("Enter", StringComparer.OrdinalIgnoreCase)); + } + + private static string GetImageKey(SearchState state) => state switch + { + SearchState.PressedEnter => "search_results", + SearchState.Typed => "search_typed", + _ => "browser_search" + }; +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/FoundryAgentsRAPI_Step15_ComputerUse.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/FoundryAgentsRAPI_Step15_ComputerUse.csproj new file mode 100644 index 0000000000..e70524fce1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/FoundryAgentsRAPI_Step15_ComputerUse.csproj @@ -0,0 +1,33 @@ + + + + Exe + net10.0 + + enable + enable + $(NoWarn);OPENAICUA001 + + + + + + + + + + + + + + Always + + + Always + + + Always + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Program.cs new file mode 100644 index 0000000000..3544894801 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/Program.cs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use Computer Use Tool with a FoundryAgentClient using the Responses API directly. + +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; +using OpenAI.Responses; + +namespace Demo.ComputerUse; + +internal sealed class Program +{ + private static async Task Main(string[] args) + { + string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); + string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "computer-use-preview"; + + const string AgentInstructions = @" + You are a computer automation assistant. + + Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see. + "; + + const string AgentName = "ComputerAgent-RAPI"; + + // Create a FoundryAgentClient with ComputerUseTool using the Responses API directly. + // No server-side agent is created. + FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: AgentName, + description: "Computer automation agent with screen interaction capabilities.", + tools: [ + ResponseTool.CreateComputerTool(ComputerToolEnvironment.Browser, 1026, 769).AsAITool(), + ]); + + await InvokeComputerUseAgentAsync(agent); + } + + private static async Task InvokeComputerUseAgentAsync(AIAgent agent) + { + // Load screenshot assets + Dictionary screenshots = ComputerUseUtil.LoadScreenshotAssets(); + + ChatOptions chatOptions = new(); + CreateResponseOptions responseCreationOptions = new() + { + TruncationMode = ResponseTruncationMode.Auto + }; + chatOptions.RawRepresentationFactory = (_) => responseCreationOptions; + ChatClientAgentRunOptions runOptions = new(chatOptions) + { + AllowBackgroundResponses = true, + }; + + ChatMessage message = new(ChatRole.User, [ + new TextContent("I need you to help me search for 'OpenAI news'. Please type 'OpenAI news' and submit the search. Once you see search results, the task is complete."), + new DataContent(new BinaryData(screenshots["browser_search"]), "image/png") + ]); + + // Initial request with screenshot - start with Bing search page + Console.WriteLine("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); + + // With RAPI (no server-side agent), we use PreviousResponseId to chain calls, + // sending only the new computer_call_output items instead of re-sending the full context. + AgentSession session = await agent.CreateSessionAsync(); + AgentResponse response = await agent.RunAsync(message, session: session, options: runOptions); + + // Main interaction loop + const int MaxIterations = 10; + int iteration = 0; + // Initialize state machine + SearchState currentState = SearchState.Initial; + + while (true) + { + // Poll until the response is complete. + while (response.ContinuationToken is { } token) + { + // Wait before polling again. + await Task.Delay(TimeSpan.FromSeconds(2)); + + // Continue with the token. + runOptions.ContinuationToken = token; + + response = await agent.RunAsync(session, runOptions); + } + + // Clear the continuation token so the next RunAsync call is a fresh request. + runOptions.ContinuationToken = null; + + Console.WriteLine($"Agent response received (ID: {response.ResponseId})"); + + if (iteration >= MaxIterations) + { + Console.WriteLine($"\nReached maximum iterations ({MaxIterations}). Stopping."); + break; + } + + iteration++; + Console.WriteLine($"\n--- Iteration {iteration} ---"); + + // Check for computer calls in the response + IEnumerable computerCallResponseItems = response.Messages + .SelectMany(x => x.Contents) + .Where(c => c.RawRepresentation is ComputerCallResponseItem and not null) + .Select(c => (ComputerCallResponseItem)c.RawRepresentation!); + + ComputerCallResponseItem? firstComputerCall = computerCallResponseItems.FirstOrDefault(); + if (firstComputerCall is null) + { + Console.WriteLine("No computer call actions found. Ending interaction."); + Console.WriteLine($"Final Response: {response}"); + break; + } + + // Process the first computer call response + ComputerCallAction action = firstComputerCall.Action; + string currentCallId = firstComputerCall.CallId; + + Console.WriteLine($"Processing computer call (ID: {currentCallId})"); + + // Simulate executing the action and taking a screenshot + (SearchState CurrentState, byte[] ImageBytes) screenInfo = ComputerUseUtil.HandleComputerActionAndTakeScreenshot(action, currentState, screenshots); + currentState = screenInfo.CurrentState; + + Console.WriteLine("Sending action result back to agent..."); + + // Send only the computer_call_output — the session carries PreviousResponseId for context continuity. + AIContent callOutput = new() + { + RawRepresentation = new ComputerCallOutputResponseItem( + currentCallId, + output: ComputerCallOutput.CreateScreenshotOutput(new BinaryData(screenInfo.ImageBytes), "image/png")) + }; + + response = await agent.RunAsync([new ChatMessage(ChatRole.User, [callOutput])], session: session, options: runOptions); + } + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/README.md new file mode 100644 index 0000000000..eb336f2b36 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step15_ComputerUse/README.md @@ -0,0 +1,29 @@ +# Computer Use with the Responses API + +This sample shows how to use the Computer Use tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Using `ResponseTool.CreateComputerTool()` with `FoundryAgentClient` +- Processing computer call actions (click, type, key press) +- Managing the computer use interaction loop with screenshots +- Handling the Azure Agents API workaround for `previous_response_id` with `computer_call_output` + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="computer-use-preview" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/FoundryAgentsRAPI_Step16_FileSearch.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/FoundryAgentsRAPI_Step16_FileSearch.csproj new file mode 100644 index 0000000000..c6c12051e1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/FoundryAgentsRAPI_Step16_FileSearch.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/Program.cs new file mode 100644 index 0000000000..57e98fc7ad --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/Program.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use File Search Tool with a FoundryAgentClient using the Responses API directly. + +using Azure.AI.Projects; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; +using OpenAI.Assistants; +using OpenAI.Files; +using OpenAI.Responses; + +string endpoint= Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +const string AgentInstructions = "You are a helpful assistant that can search through uploaded files to answer questions."; + +// We need the AIProjectClient to upload files and create vector stores. +AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential()); +var projectOpenAIClient = aiProjectClient.GetProjectOpenAIClient(); +var filesClient = projectOpenAIClient.GetProjectFilesClient(); +var vectorStoresClient = projectOpenAIClient.GetProjectVectorStoresClient(); + +// 1. Create a temp file with test content and upload it. +string searchFilePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + "_lookup.txt"); +File.WriteAllText( + path: searchFilePath, + contents: """ + Employee Directory: + - Alice Johnson, 28 years old, Software Engineer, Engineering Department + - Bob Smith, 35 years old, Sales Manager, Sales Department + - Carol Williams, 42 years old, HR Director, Human Resources Department + - David Brown, 31 years old, Customer Support Lead, Support Department + """ +); + +Console.WriteLine($"Uploading file: {searchFilePath}"); +OpenAIFile uploadedFile = filesClient.UploadFile( + filePath: searchFilePath, + purpose: FileUploadPurpose.Assistants +); +Console.WriteLine($"Uploaded file, file ID: {uploadedFile.Id}"); + +// 2. Create a vector store with the uploaded file. +var vectorStoreResult = await vectorStoresClient.CreateVectorStoreAsync( + options: new() { FileIds = { uploadedFile.Id }, Name = "EmployeeDirectory_VectorStore" } +); +string vectorStoreId = vectorStoreResult.Value.Id; +Console.WriteLine($"Created vector store, vector store ID: {vectorStoreId}"); + +// Create a FoundryAgentClient with HostedFileSearchTool using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: "FileSearchAgent-RAPI", + tools: [new HostedFileSearchTool() { Inputs = [new HostedVectorStoreContent(vectorStoreId)] }]); + +// Run the agent +Console.WriteLine("\n--- Running File Search Agent ---"); +AgentResponse response = await agent.RunAsync("Who is the youngest employee?"); +Console.WriteLine($"Response: {response}"); + +// Getting any file citation annotations generated by the tool +foreach (AIAnnotation annotation in response.Messages.SelectMany(m => m.Contents).SelectMany(c => c.Annotations ?? [])) +{ + if (annotation.RawRepresentation is TextAnnotationUpdate citationAnnotation) + { + Console.WriteLine($$""" + File Citation: + File Id: {{citationAnnotation.OutputFileId}} + Text to Replace: {{citationAnnotation.TextToReplace}} + """); + } +} + +// Cleanup file resources (no agent cleanup needed - no server-side agent was created). +Console.WriteLine("\n--- Cleanup ---"); +await vectorStoresClient.DeleteVectorStoreAsync(vectorStoreId); +await filesClient.DeleteFileAsync(uploadedFile.Id); +File.Delete(searchFilePath); +Console.WriteLine("Cleanup completed successfully."); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/README.md new file mode 100644 index 0000000000..86f07eea16 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step16_FileSearch/README.md @@ -0,0 +1,29 @@ +# File Search with the Responses API + +This sample shows how to use the File Search tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Uploading files and creating vector stores via `AIProjectClient` +- Using `HostedFileSearchTool` with `FoundryAgentClient` +- Handling file citation annotations in agent responses +- Cleaning up file resources after use + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/FoundryAgentsRAPI_Step17_OpenAPITools.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/FoundryAgentsRAPI_Step17_OpenAPITools.csproj new file mode 100644 index 0000000000..c6c12051e1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/FoundryAgentsRAPI_Step17_OpenAPITools.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/Program.cs new file mode 100644 index 0000000000..8cadddc449 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/Program.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use OpenAPI Tools with a FoundryAgentClient using the Responses API directly. + +using Azure.AI.Projects.OpenAI; +using Azure.Identity; +using Microsoft.Agents.AI.AzureAI; +using OpenAI.Responses; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +const string AgentInstructions = "You are a helpful assistant that can use the countries API to retrieve information about countries by their currency code."; + +// A simple OpenAPI specification for the REST Countries API +const string CountriesOpenApiSpec = """ +{ + "openapi": "3.1.0", + "info": { + "title": "REST Countries API", + "description": "Retrieve information about countries by currency code", + "version": "v3.1" + }, + "servers": [ + { + "url": "https://restcountries.com/v3.1" + } + ], + "paths": { + "/currency/{currency}": { + "get": { + "description": "Get countries that use a specific currency code (e.g., USD, EUR, GBP)", + "operationId": "GetCountriesByCurrency", + "parameters": [ + { + "name": "currency", + "in": "path", + "description": "Currency code (e.g., USD, EUR, GBP)", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response with list of countries", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + }, + "404": { + "description": "No countries found for the currency" + } + } + } + } + } +} +"""; + +// Create the OpenAPI function definition +var openApiFunction = new OpenAPIFunctionDefinition( + "get_countries", + BinaryData.FromString(CountriesOpenApiSpec), + new OpenAPIAnonymousAuthenticationDetails()) +{ + Description = "Retrieve information about countries by currency code" +}; + +// Create a FoundryAgentClient with OpenAPI tool using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: "OpenAPIToolsAgent-RAPI", + tools: [((ResponseTool)AgentTool.CreateOpenApiTool(openApiFunction)).AsAITool()]); + +// Run the agent with a question about countries +Console.WriteLine(await agent.RunAsync("What countries use the Euro (EUR) as their currency? Please list them.")); diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/README.md new file mode 100644 index 0000000000..ed8e531168 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step17_OpenAPITools/README.md @@ -0,0 +1,29 @@ +# OpenAPI Tools with the Responses API + +This sample shows how to use OpenAPI tools with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Defining an OpenAPI specification inline +- Creating an `OpenAPIFunctionDefinition` for the REST Countries API +- Using `AgentTool.CreateOpenApiTool()` with `FoundryAgentClient` +- Server-side execution of OpenAPI tool calls + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/FoundryAgentsRAPI_Step18_BingCustomSearch.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/FoundryAgentsRAPI_Step18_BingCustomSearch.csproj new file mode 100644 index 0000000000..c6c12051e1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/FoundryAgentsRAPI_Step18_BingCustomSearch.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/Program.cs new file mode 100644 index 0000000000..9a657f39e3 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/Program.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use Bing Custom Search Tool with a FoundryAgentClient using the Responses API directly. + +using Azure.AI.Projects.OpenAI; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using OpenAI.Responses; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; +string connectionId = Environment.GetEnvironmentVariable("AZURE_AI_CUSTOM_SEARCH_CONNECTION_ID") ?? throw new InvalidOperationException("AZURE_AI_CUSTOM_SEARCH_CONNECTION_ID is not set."); +string instanceName = Environment.GetEnvironmentVariable("AZURE_AI_CUSTOM_SEARCH_INSTANCE_NAME") ?? throw new InvalidOperationException("AZURE_AI_CUSTOM_SEARCH_INSTANCE_NAME is not set."); + +const string AgentInstructions = """ + You are a helpful agent that can use Bing Custom Search tools to assist users. + Use the available Bing Custom Search tools to answer questions and perform tasks. + """; + +// Bing Custom Search tool parameters +BingCustomSearchToolParameters bingCustomSearchToolParameters = new([ + new BingCustomSearchConfiguration(connectionId, instanceName) +]); + +// Create a FoundryAgentClient with Bing Custom Search tool using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: "BingCustomSearchAgent-RAPI", + tools: [((ResponseTool)AgentTool.CreateBingCustomSearchTool(bingCustomSearchToolParameters)).AsAITool()]); + +Console.WriteLine($"Created agent: {agent.Name}"); + +// Run the agent with a search query +AgentResponse response = await agent.RunAsync("Search for the latest news about Microsoft AI"); + +Console.WriteLine("\n=== Agent Response ==="); +foreach (var message in response.Messages) +{ + Console.WriteLine(message.Text); +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/README.md new file mode 100644 index 0000000000..11d9d70762 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step18_BingCustomSearch/README.md @@ -0,0 +1,36 @@ +# Bing Custom Search with the Responses API + +This sample shows how to use the Bing Custom Search tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Configuring `BingCustomSearchToolParameters` with connection ID and instance name +- Using `AgentTool.CreateBingCustomSearchTool()` with `FoundryAgentClient` +- Processing search results from agent responses + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) +- Bing Custom Search resource configured with a connection ID + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +$env:AZURE_AI_CUSTOM_SEARCH_CONNECTION_ID="your-connection-id" # The full ARM resource URI, e.g., "/subscriptions/.../connections/your-bing-connection" +$env:AZURE_AI_CUSTOM_SEARCH_INSTANCE_NAME="your-instance-name" # The Bing Custom Search configuration name (from Azure portal) +``` + +### Finding the connection ID and instance name + +- **Connection ID** (`AZURE_AI_CUSTOM_SEARCH_CONNECTION_ID`): The full ARM resource URI including the `/projects//connections/` segment. Find the connection name in your Foundry project under **Management center** → **Connected resources**. +- **Instance Name** (`AZURE_AI_CUSTOM_SEARCH_INSTANCE_NAME`): The **configuration name** from your Bing Custom Search resource (Azure portal → your Bing Custom Search resource → **Configurations**). This is _not_ the Azure resource name or the connection name — it's the name of the specific search configuration that defines which domains/sites to search against. + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/FoundryAgentsRAPI_Step19_SharePoint.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/FoundryAgentsRAPI_Step19_SharePoint.csproj new file mode 100644 index 0000000000..c6c12051e1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/FoundryAgentsRAPI_Step19_SharePoint.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/Program.cs new file mode 100644 index 0000000000..7583003fe1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/Program.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use SharePoint Grounding Tool with a FoundryAgentClient using the Responses API directly. + +using Azure.AI.Projects.OpenAI; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using OpenAI.Responses; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; +string sharepointConnectionId = Environment.GetEnvironmentVariable("SHAREPOINT_PROJECT_CONNECTION_ID") ?? throw new InvalidOperationException("SHAREPOINT_PROJECT_CONNECTION_ID is not set."); + +const string AgentInstructions = """ + You are a helpful agent that can use SharePoint tools to assist users. + Use the available SharePoint tools to answer questions and perform tasks. + """; + +// Create SharePoint tool options with project connection +var sharepointOptions = new SharePointGroundingToolOptions(); +sharepointOptions.ProjectConnections.Add(new ToolProjectConnection(sharepointConnectionId)); + +// Create a FoundryAgentClient with SharePoint tool using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: "SharePointAgent-RAPI", + tools: [((ResponseTool)AgentTool.CreateSharepointTool(sharepointOptions)).AsAITool()]); + +Console.WriteLine($"Created agent: {agent.Name}"); + +AgentResponse response = await agent.RunAsync("List the documents available in SharePoint"); + +// Display the response +Console.WriteLine("\n=== Agent Response ==="); +Console.WriteLine(response); + +// Display grounding annotations if any +foreach (var message in response.Messages) +{ + foreach (var content in message.Contents) + { + if (content.Annotations is not null) + { + foreach (var annotation in content.Annotations) + { + Console.WriteLine($"Annotation: {annotation}"); + } + } + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/README.md new file mode 100644 index 0000000000..ff6c982860 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step19_SharePoint/README.md @@ -0,0 +1,30 @@ +# SharePoint Grounding with the Responses API + +This sample shows how to use the SharePoint Grounding tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Configuring `SharePointGroundingToolOptions` with project connections +- Using `AgentTool.CreateSharepointTool()` with `FoundryAgentClient` +- Displaying grounding annotations from agent responses + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) +- SharePoint connection configured in your Microsoft Foundry project + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +$env:SHAREPOINT_PROJECT_CONNECTION_ID="your-sharepoint-connection-id" # The full ARM resource URI, e.g., "/subscriptions/.../connections/SharepointTestTool" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/FoundryAgentsRAPI_Step20_MicrosoftFabric.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/FoundryAgentsRAPI_Step20_MicrosoftFabric.csproj new file mode 100644 index 0000000000..0cdfd801ed --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/FoundryAgentsRAPI_Step20_MicrosoftFabric.csproj @@ -0,0 +1,20 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/Program.cs new file mode 100644 index 0000000000..167f2a3619 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/Program.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use Microsoft Fabric Tool with a FoundryAgentClient using the Responses API directly. + +using Azure.AI.Projects.OpenAI; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using OpenAI.Responses; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; +string fabricConnectionId = Environment.GetEnvironmentVariable("FABRIC_PROJECT_CONNECTION_ID") ?? throw new InvalidOperationException("FABRIC_PROJECT_CONNECTION_ID is not set."); + +const string AgentInstructions = "You are a helpful assistant with access to Microsoft Fabric data. Answer questions based on data available through your Fabric connection."; + +// Configure Microsoft Fabric tool options with project connection +var fabricToolOptions = new FabricDataAgentToolOptions(); +fabricToolOptions.ProjectConnections.Add(new ToolProjectConnection(fabricConnectionId)); + +// Create a FoundryAgentClient with Microsoft Fabric tool using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: "FabricAgent-RAPI", + tools: [((ResponseTool)AgentTool.CreateMicrosoftFabricTool(fabricToolOptions)).AsAITool()]); + +Console.WriteLine($"Created agent: {agent.Name}"); + +// Run the agent with a sample query +AgentResponse response = await agent.RunAsync("What data is available in the connected Fabric workspace?"); + +Console.WriteLine("\n=== Agent Response ==="); +foreach (var message in response.Messages) +{ + Console.WriteLine(message.Text); +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/README.md new file mode 100644 index 0000000000..7e66b30322 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step20_MicrosoftFabric/README.md @@ -0,0 +1,30 @@ +# Microsoft Fabric with the Responses API + +This sample shows how to use the Microsoft Fabric tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Configuring `FabricDataAgentToolOptions` with project connections +- Using `AgentTool.CreateMicrosoftFabricTool()` with `FoundryAgentClient` +- Querying data available through a Fabric connection + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) +- Microsoft Fabric connection configured in your Microsoft Foundry project + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +$env:FABRIC_PROJECT_CONNECTION_ID="your-fabric-connection-id" # The full ARM resource URI, e.g., "/subscriptions/.../connections/FabricTestTool" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/FoundryAgentsRAPI_Step21_WebSearch.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/FoundryAgentsRAPI_Step21_WebSearch.csproj new file mode 100644 index 0000000000..c6c12051e1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/FoundryAgentsRAPI_Step21_WebSearch.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/Program.cs new file mode 100644 index 0000000000..f052d0e2ef --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/Program.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample shows how to use the Web Search Tool with a FoundryAgentClient using the Responses API directly. + +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; +using OpenAI.Responses; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +const string AgentInstructions = "You are a helpful assistant that can search the web to find current information and answer questions accurately."; +const string AgentName = "WebSearchAgent-RAPI"; + +// Create a FoundryAgentClient with HostedWebSearchTool using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: AgentName, + tools: [new HostedWebSearchTool()]); + +AgentResponse response = await agent.RunAsync("What's the weather today in Seattle?"); + +// Get the text response +Console.WriteLine($"Response: {response.Text}"); + +// Getting any annotations/citations generated by the web search tool +foreach (AIAnnotation annotation in response.Messages.SelectMany(m => m.Contents).SelectMany(c => c.Annotations ?? [])) +{ + Console.WriteLine($"Annotation: {annotation}"); + if (annotation.RawRepresentation is UriCitationMessageAnnotation urlCitation) + { + Console.WriteLine($$""" + Title: {{urlCitation.Title}} + URL: {{urlCitation.Uri}} + """); + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/README.md new file mode 100644 index 0000000000..78f221dcf1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step21_WebSearch/README.md @@ -0,0 +1,28 @@ +# Web Search with the Responses API + +This sample shows how to use the Web Search tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Using `HostedWebSearchTool` with `FoundryAgentClient` +- Processing web search citations and annotations +- Extracting URL citation details (title, URL) from responses + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/FoundryAgentsRAPI_Step22_MemorySearch.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/FoundryAgentsRAPI_Step22_MemorySearch.csproj new file mode 100644 index 0000000000..c6c12051e1 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/FoundryAgentsRAPI_Step22_MemorySearch.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/Program.cs new file mode 100644 index 0000000000..c5e0864b44 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/Program.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample demonstrates how to use the Memory Search Tool with a FoundryAgentClient using the Responses API directly. +// Memories are explicitly stored first via the MemoryStores API, then the MemorySearchPreviewTool +// is used by the agent to retrieve them during conversation. + +using Azure.AI.Projects; +using Azure.AI.Projects.OpenAI; +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using OpenAI.Responses; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; +string embeddingModelName = Environment.GetEnvironmentVariable("AZURE_AI_EMBEDDING_DEPLOYMENT_NAME") ?? "text-embedding-ada-002"; +string memoryStoreName = Environment.GetEnvironmentVariable("AZURE_AI_MEMORY_STORE_ID") ?? $"rapi-memory-sample-{Guid.NewGuid():N}"; + +const string AgentName = "MemorySearchAgent-RAPI"; +string memoryScope = "travel-preferences"; + +DefaultAzureCredential credential = new(); +AIProjectClient aiProjectClient = new(new Uri(endpoint), credential); + +// Ensure the memory store exists and has memories to retrieve. +await EnsureMemoryStoreAsync(); + +try +{ + // Create a FoundryAgentClient with the Memory Search tool. + // The tool retrieves memories — it does NOT store new ones during conversation. + MemorySearchPreviewTool memorySearchTool = new(memoryStoreName, memoryScope) { UpdateDelay = 0 }; + + FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: credential, + model: deploymentName, + instructions: "You are a helpful travel assistant. Use the memory search tool to recall what you know about the user from past conversations.", + name: AgentName, + tools: [((ResponseTool)memorySearchTool).AsAITool()]); + + Console.WriteLine("Agent created. Asking about previously stored memories...\n"); + + // The agent uses the memory search tool to recall stored information. + Console.WriteLine("User: What do you remember about my upcoming trip?"); + AgentResponse response = await agent.RunAsync("What do you remember about my upcoming trip?"); + Console.WriteLine($"Agent: {response.Messages.LastOrDefault()?.Text}\n"); + + // Inspect memory search results if available in raw response items. + foreach (var message in response.Messages) + { + if (message.RawRepresentation is MemorySearchToolCallResponseItem memorySearchResult) + { + Console.WriteLine($"Memory Search Status: {memorySearchResult.Status}"); + Console.WriteLine($"Memory Search Results Count: {memorySearchResult.Results.Count}"); + + foreach (var result in memorySearchResult.Results) + { + var memoryItem = result.MemoryItem; + Console.WriteLine($" - Memory ID: {memoryItem.MemoryId}"); + Console.WriteLine($" Scope: {memoryItem.Scope}"); + Console.WriteLine($" Content: {memoryItem.Content}"); + Console.WriteLine($" Updated: {memoryItem.UpdatedAt}"); + } + } + } +} +finally +{ + // Cleanup: Delete the memory store. + Console.WriteLine($"\nCleaning up memory store '{memoryStoreName}'..."); + await aiProjectClient.MemoryStores.DeleteMemoryStoreAsync(memoryStoreName); + Console.WriteLine("Memory store deleted."); +} + +// This creates a temporary memory to demonstrate the memory search functionality. +// In normal usage, the memories should be already present to be used by the tool. +async Task EnsureMemoryStoreAsync() +{ + // Create the store if it doesn't already exist. + Console.WriteLine($"Creating memory store '{memoryStoreName}'..."); + try + { + await aiProjectClient.MemoryStores.GetMemoryStoreAsync(memoryStoreName); + Console.WriteLine("Memory store already exists."); + } + catch (System.ClientModel.ClientResultException ex) when (ex.Status == 404) + { + MemoryStoreDefaultDefinition definition = new(deploymentName, embeddingModelName); + await aiProjectClient.MemoryStores.CreateMemoryStoreAsync(memoryStoreName, definition, "Sample memory store for RAPI Memory Search demo"); + Console.WriteLine("Memory store created."); + } + + // Explicitly add memories from a simulated prior conversation. + Console.WriteLine("Storing memories from a prior conversation..."); + MemoryUpdateOptions memoryOptions = new(memoryScope) { UpdateDelay = 0 }; + memoryOptions.Items.Add(ResponseItem.CreateUserMessageItem("My name is Alice and I'm planning a trip to Japan next spring.")); + + MemoryUpdateResult updateResult = await aiProjectClient.MemoryStores.WaitForMemoriesUpdateAsync( + memoryStoreName: memoryStoreName, + options: memoryOptions, + pollingInterval: 500); + + if (updateResult.Status == MemoryStoreUpdateStatus.Failed) + { + throw new InvalidOperationException($"Memory update failed: {updateResult.ErrorDetails}"); + } + + Console.WriteLine($"Memory update completed (status: {updateResult.Status})."); + + // Quick verification that memories are searchable. + Console.WriteLine("Verifying stored memories..."); + MemorySearchOptions searchOptions = new(memoryScope) + { + Items = { ResponseItem.CreateUserMessageItem("What are Alice's travel preferences?") } + }; + MemoryStoreSearchResponse searchResult = await aiProjectClient.MemoryStores.SearchMemoriesAsync( + memoryStoreName: memoryStoreName, + options: searchOptions); + + foreach (var memory in searchResult.Memories) + { + Console.WriteLine($" - {memory.MemoryItem.Content}"); + } + + Console.WriteLine(); +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/README.md new file mode 100644 index 0000000000..13da1dc9e0 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step22_MemorySearch/README.md @@ -0,0 +1,31 @@ +# Memory Search with the Responses API + +This sample demonstrates how to use the Memory Search tool with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Configuring `MemorySearchPreviewTool` with a memory store and user scope +- Using memory search for cross-conversation recall +- Inspecting `MemorySearchToolCallResponseItem` results +- User profile persistence across conversations + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) +- A memory store created beforehand via Azure Portal or Python SDK + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +$env:AZURE_AI_MEMORY_STORE_ID="your-memory-store-name" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/FoundryAgentsRAPI_Step23_LocalMCP.csproj b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/FoundryAgentsRAPI_Step23_LocalMCP.csproj new file mode 100644 index 0000000000..a69c81f08c --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/FoundryAgentsRAPI_Step23_LocalMCP.csproj @@ -0,0 +1,20 @@ + + + + Exe + net10.0 + + enable + enable + + + + + + + + + + + + diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/Program.cs b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/Program.cs new file mode 100644 index 0000000000..a131e3188d --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/Program.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft. All rights reserved. + +// This sample demonstrates how to use a local MCP (Model Context Protocol) client with a FoundryAgentClient +// using the Responses API directly. The MCP tools are resolved locally by connecting directly to the MCP +// server via HTTP, and then passed to the agent as client-side tools. + +using Azure.Identity; +using Microsoft.Agents.AI; +using Microsoft.Agents.AI.AzureAI; +using Microsoft.Extensions.AI; +using ModelContextProtocol.Client; + +string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); +string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; + +const string AgentInstructions = "You are a helpful assistant that can help with Microsoft documentation questions. Use the Microsoft Learn MCP tool to search for documentation."; +const string AgentName = "DocsAgent-RAPI"; + +// Connect to the MCP server locally via HTTP (Streamable HTTP transport). +Console.WriteLine("Connecting to MCP server at https://learn.microsoft.com/api/mcp ..."); + +await using McpClient mcpClient = await McpClient.CreateAsync(new HttpClientTransport(new() +{ + Endpoint = new Uri("https://learn.microsoft.com/api/mcp"), + Name = "Microsoft Learn MCP", +})); + +// Retrieve the list of tools available on the MCP server (resolved locally). +IList mcpTools = await mcpClient.ListToolsAsync(); +Console.WriteLine($"MCP tools available: {string.Join(", ", mcpTools.Select(t => t.Name))}"); + +// Wrap each MCP tool with a DelegatingAIFunction to log local invocations. +List wrappedTools = mcpTools.Select(tool => (AITool)new LoggingMcpTool(tool)).ToList(); + +// Create a FoundryAgentClient with the locally-resolved MCP tools using the Responses API directly. +// No server-side agent is created. +FoundryResponsesAgent agent = new( + endpoint: new Uri(endpoint), + tokenProvider: new DefaultAzureCredential(), + model: deploymentName, + instructions: AgentInstructions, + name: AgentName, + tools: wrappedTools); + +Console.WriteLine($"Agent '{agent.Name}' created successfully."); + +// First query +const string Prompt1 = "How does one create an Azure storage account using az cli?"; +Console.WriteLine($"\nUser: {Prompt1}\n"); +AgentResponse response1 = await agent.RunAsync(Prompt1); +Console.WriteLine($"Agent: {response1}"); + +Console.WriteLine("\n=======================================\n"); + +// Second query +const string Prompt2 = "What is Microsoft Agent Framework?"; +Console.WriteLine($"User: {Prompt2}\n"); +AgentResponse response2 = await agent.RunAsync(Prompt2); +Console.WriteLine($"Agent: {response2}"); + +/// +/// Wraps an MCP tool to log when it is invoked locally, +/// confirming that the MCP call is happening client-side. +/// +internal sealed class LoggingMcpTool(AIFunction innerFunction) : DelegatingAIFunction(innerFunction) +{ + protected override ValueTask InvokeCoreAsync(AIFunctionArguments arguments, CancellationToken cancellationToken) + { + Console.WriteLine($" >> [LOCAL MCP] Invoking tool '{this.Name}' locally..."); + return base.InvokeCoreAsync(arguments, cancellationToken); + } +} diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/README.md new file mode 100644 index 0000000000..77ba9d3ce8 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/FoundryAgentsRAPI_Step23_LocalMCP/README.md @@ -0,0 +1,29 @@ +# Local MCP with the Responses API + +This sample demonstrates how to use a local MCP (Model Context Protocol) client with a `FoundryAgentClient` using the Responses API directly. + +## What this sample demonstrates + +- Connecting to an MCP server via HTTP (Streamable HTTP transport) +- Resolving MCP tools locally and wrapping them with logging +- Using `DelegatingAIFunction` to add custom behavior to MCP tools +- Passing locally-resolved MCP tools to `FoundryAgentClient` + +## Prerequisites + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and deployment configured +- Azure CLI installed and authenticated (`az login`) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +## Run the sample + +```powershell +dotnet run +``` diff --git a/dotnet/samples/02-agents/FoundryResponseAgents/README.md b/dotnet/samples/02-agents/FoundryResponseAgents/README.md new file mode 100644 index 0000000000..796dd7eb20 --- /dev/null +++ b/dotnet/samples/02-agents/FoundryResponseAgents/README.md @@ -0,0 +1,101 @@ +# Getting started with Foundry Response Agents + +These samples demonstrate how to use the `FoundryAgentClient` (backed by the **Responses API**) to work with +Microsoft Foundry models directly, without creating server-side agent definitions. + +## How these differ from [Foundry Agents](../FoundryAgents/README.md) + +| | **Foundry Agents** | **Foundry Response Agents** | +|---|---|---| +| **Server-side agent** | Yes — agent is created, versioned, and managed in the Foundry service | No — instructions, tools, and options live entirely in your code | +| **Versioning** | Agent versions are immutable; behavior is locked at creation time | No versioning; agent behavior changes when you redeploy code | +| **Lifecycle** | Create → Run → Delete | Instantiate → Run (nothing to clean up) | +| **Backing API** | Foundry Agents API (`GetProjectResponsesClientForAgent`) | Responses API (`GetProjectResponsesClientForModel`) | +| **Type** | `AIAgent` via `AIProjectClient.CreateAIAgentAsync` | `FoundryAgentClient` (wraps `ChatClientAgent` internally) | + +Choose **Foundry Agents** when you need managed, versioned agent definitions visible in the Foundry portal. +Choose **Foundry Response Agents** when you want a lightweight, code-first agent with no server-side state. + +## Prerequisites + +Before you begin, ensure you have the following prerequisites: + +- .NET 10 SDK or later +- Microsoft Foundry service endpoint and project configured +- Azure CLI installed and authenticated (for Azure credential authentication) + +Set the following environment variables: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +The `FoundryAgentClient` auto-discovers these environment variables at construction time, so no endpoint or credential code is needed in the samples. + +## Samples + +|Sample|Description| +|---|---| +|[Basics](./FoundryAgentsRAPI_Step01_Basics/)|This sample demonstrates how to create and run a basic agent using the Responses API| +|[Multi-turn conversation](./FoundryAgentsRAPI_Step02_MultiturnConversation/)|This sample demonstrates how to implement a multi-turn conversation using the Responses API| +|[Using function tools](./FoundryAgentsRAPI_Step03_UsingFunctionTools/)|This sample demonstrates how to use function tools with the Responses API| +|[Using function tools with approvals](./FoundryAgentsRAPI_Step04_UsingFunctionToolsWithApprovals/)|This sample demonstrates how to use function tools with human-in-the-loop approval| +|[Structured output](./FoundryAgentsRAPI_Step05_StructuredOutput/)|This sample demonstrates how to use structured output with the Responses API| +|[Persisted conversations](./FoundryAgentsRAPI_Step06_PersistedConversations/)|This sample demonstrates how to persist and resume conversations| +|[Observability](./FoundryAgentsRAPI_Step07_Observability/)|This sample demonstrates how to add OpenTelemetry observability| +|[Dependency injection](./FoundryAgentsRAPI_Step08_DependencyInjection/)|This sample demonstrates how to use dependency injection with a hosted service| +|[Using images](./FoundryAgentsRAPI_Step10_UsingImages/)|This sample demonstrates how to use image multi-modality| +|[Agent as function tool](./FoundryAgentsRAPI_Step11_AsFunctionTool/)|This sample demonstrates how to use one agent as a function tool for another| +|[Middleware](./FoundryAgentsRAPI_Step12_Middleware/)|This sample demonstrates multiple middleware layers (PII, guardrails, approvals)| +|[Using MCP client as tools](./FoundryAgentsRAPI_Step09_UsingMcpClientAsTools/)|This sample demonstrates how to use MCP client tools with the Responses API| +|[Plugins](./FoundryAgentsRAPI_Step13_Plugins/)|This sample demonstrates how to use plugins with dependency injection| +|[Code interpreter](./FoundryAgentsRAPI_Step14_CodeInterpreter/)|This sample demonstrates how to use the code interpreter tool| +|[Computer use](./FoundryAgentsRAPI_Step15_ComputerUse/)|This sample demonstrates how to use the computer use tool| +|[File search](./FoundryAgentsRAPI_Step16_FileSearch/)|This sample demonstrates how to use the file search tool| +|[OpenAPI tools](./FoundryAgentsRAPI_Step17_OpenAPITools/)|This sample demonstrates how to use OpenAPI tools| +|[Bing custom search](./FoundryAgentsRAPI_Step18_BingCustomSearch/)|This sample demonstrates how to use the Bing Custom Search tool| +|[SharePoint](./FoundryAgentsRAPI_Step19_SharePoint/)|This sample demonstrates how to use the SharePoint grounding tool| +|[Microsoft Fabric](./FoundryAgentsRAPI_Step20_MicrosoftFabric/)|This sample demonstrates how to use the Microsoft Fabric tool| +|[Web search](./FoundryAgentsRAPI_Step21_WebSearch/)|This sample demonstrates how to use the web search tool| +|[Memory search](./FoundryAgentsRAPI_Step22_MemorySearch/)|This sample demonstrates how to use the memory search tool| +|[Local MCP](./FoundryAgentsRAPI_Step23_LocalMCP/)|This sample demonstrates how to use a local MCP client with HTTP transport| + +## Running the samples from the console + +To run the samples, navigate to the desired sample directory, e.g. + +```powershell +cd FoundryAgentsRAPI_Step01_Basics +``` + +Ensure the following environment variables are set: + +```powershell +$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project" +$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" +``` + +Execute the following command to build the sample: + +```powershell +dotnet build +``` + +Execute the following command to run the sample: + +```powershell +dotnet run --no-build +``` + +Or just build and run in one step: + +```powershell +dotnet run +``` + +## Running the samples from Visual Studio + +Open the solution in Visual Studio and set the desired sample project as the startup project. Then, run the project using the built-in debugger or by pressing `F5`. + +You will be prompted for any required environment variables if they are not already set. diff --git a/dotnet/samples/02-agents/README.md b/dotnet/samples/02-agents/README.md index b901645f88..31bdc5a679 100644 --- a/dotnet/samples/02-agents/README.md +++ b/dotnet/samples/02-agents/README.md @@ -8,7 +8,8 @@ of the agent framework. |Sample|Description| |---|---| |[Agents](./Agents/README.md)|Step by step instructions for getting started with agents| -|[Foundry Agents](./FoundryAgents/README.md)|Getting started with Azure Foundry Agents| +|[Foundry Agents](./FoundryAgents/README.md)|Getting started with Microsoft Foundry Agents (server-side, versioned)| +|[Foundry Response Agents](./FoundryResponseAgents/README.md)|Getting started with `FoundryAgentClient` using the Responses API (code-first, no server-side agent)| |[Agent Providers](./AgentProviders/README.md)|Getting started with creating agents using various providers| |[Agents With Retrieval Augmented Generation (RAG)](./AgentWithRAG/README.md)|Adding Retrieval Augmented Generation (RAG) capabilities to your agents.| |[Agents With Memory](./AgentWithMemory/README.md)|Adding Memory capabilities to your agents.| diff --git a/dotnet/src/Microsoft.Agents.AI.AzureAI/FoundryResponsesAgent.cs b/dotnet/src/Microsoft.Agents.AI.AzureAI/FoundryResponsesAgent.cs new file mode 100644 index 0000000000..f077cda7b6 --- /dev/null +++ b/dotnet/src/Microsoft.Agents.AI.AzureAI/FoundryResponsesAgent.cs @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft. All rights reserved. + +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using Azure.AI.Projects; +using Azure.Identity; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; +using Microsoft.Shared.DiagnosticIds; +using Microsoft.Shared.Diagnostics; + +namespace Microsoft.Agents.AI.AzureAI; + +/// +/// Provides an that uses an Microsoft Foundry project as its backing service. +/// +/// +/// This agent internally creates an and a +/// backed by the project's Responses API. All operations are delegated to the internal . +/// +[Experimental(DiagnosticIds.Experiments.AIOpenAIResponses)] +public sealed class FoundryResponsesAgent : AIAgent +{ + private const string ProjectEndpointEnvVar = "AZURE_AI_PROJECT_ENDPOINT"; + private const string ModelDeploymentEnvVar = "AZURE_AI_MODEL_DEPLOYMENT_NAME"; + + private readonly AIProjectClient _aiProjectClient; + private readonly ChatClientAgent _innerAgent; + private readonly AIAgentMetadata _metadata = new("microsoft.foundry"); + + /// + /// Initializes a new instance of the class using environment variables for configuration. + /// + /// Optional system instructions that guide the agent's behavior. + /// Optional name for the agent. + /// Optional human-readable description of the agent's purpose and capabilities. + /// Optional collection of tools that the agent can invoke during conversations. + /// Provides a way to customize the creation of the underlying used by the agent. + /// Optional logger factory for creating loggers used by the agent. + /// Optional service provider for resolving dependencies required by AI functions. + /// The AZURE_AI_PROJECT_ENDPOINT environment variable is not set. + /// + /// + /// This constructor reads the following environment variables: + /// + /// AZURE_AI_PROJECT_ENDPOINT (required) — The Microsoft Foundry project endpoint URL. + /// AZURE_AI_MODEL_DEPLOYMENT_NAME (optional) — The model deployment name to use. + /// + /// + /// Authentication uses . + /// + public FoundryResponsesAgent( + string? instructions = null, + string? name = null, + string? description = null, + IList? tools = null, + Func? chatClientFactory = null, + ILoggerFactory? loggerFactory = null, + IServiceProvider? services = null) + : this( + new Uri(Environment.GetEnvironmentVariable(ProjectEndpointEnvVar) + ?? throw new InvalidOperationException($"Environment variable '{ProjectEndpointEnvVar}' is not set.")), + new DefaultAzureCredential(), + Environment.GetEnvironmentVariable(ModelDeploymentEnvVar) + ?? throw new InvalidOperationException($"Environment variable '{ModelDeploymentEnvVar}' is not set."), + clientOptions: null, + instructions, + name, + description, + tools, + chatClientFactory, + loggerFactory, + services) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The Microsoft Foundry project endpoint. + /// The authentication token provider used to authenticate with the Microsoft Foundry service. + /// The model deployment name to use for the agent (e.g., "gpt-4o-mini"). + /// Optional configuration options for the . + /// Optional system instructions that guide the agent's behavior. + /// Optional name for the agent. + /// Optional human-readable description of the agent's purpose and capabilities. + /// Optional collection of tools that the agent can invoke during conversations. + /// Provides a way to customize the creation of the underlying used by the agent. + /// Optional logger factory for creating loggers used by the agent. + /// Optional service provider for resolving dependencies required by AI functions. + /// or is . + public FoundryResponsesAgent( + Uri endpoint, + AuthenticationTokenProvider tokenProvider, + string model, + AIProjectClientOptions? clientOptions = null, + string? instructions = null, + string? name = null, + string? description = null, + IList? tools = null, + Func? chatClientFactory = null, + ILoggerFactory? loggerFactory = null, + IServiceProvider? services = null) + : this( + endpoint, + tokenProvider, + clientOptions, + new ChatClientAgentOptions + { + ChatOptions = new ChatOptions + { + ModelId = Throw.IfNullOrWhitespace(model), + Tools = tools, + Instructions = instructions + }, + Name = name, + Description = description + }, + chatClientFactory, + loggerFactory, + services) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The Microsoft Foundry project endpoint. + /// The authentication token provider used to authenticate with the Microsoft Foundry service. + /// Optional configuration options for the . + /// Configuration options that control all aspects of the agent's behavior. + /// Provides a way to customize the creation of the underlying used by the agent. + /// Optional logger factory for creating loggers used by the agent. + /// Optional service provider for resolving dependencies required by AI functions. + /// or is . + public FoundryResponsesAgent( + Uri endpoint, + AuthenticationTokenProvider tokenProvider, + AIProjectClientOptions? clientOptions = null, + ChatClientAgentOptions? options = null, + Func? chatClientFactory = null, + ILoggerFactory? loggerFactory = null, + IServiceProvider? services = null) + { + Throw.IfNull(endpoint); + Throw.IfNull(tokenProvider); + + clientOptions ??= new AIProjectClientOptions(); + clientOptions.AddPolicy(RequestOptionsExtensions.UserAgentPolicy, PipelinePosition.PerCall); + + this._aiProjectClient = new AIProjectClient(endpoint, tokenProvider, clientOptions); + + IChatClient chatClient = this._aiProjectClient + .OpenAI + .GetProjectResponsesClientForModel(options?.ChatOptions?.ModelId ?? string.Empty) + .AsIChatClient(); + + if (chatClientFactory is not null) + { + chatClient = chatClientFactory(chatClient); + } + + this._innerAgent = new ChatClientAgent(chatClient, options, loggerFactory, services); + } + + /// + protected override string? IdCore => this._innerAgent.Id; + + /// + public override string? Name => this._innerAgent.Name; + + /// + public override string? Description => this._innerAgent.Description; + + /// + public override object? GetService(Type serviceType, object? serviceKey = null) + { + return base.GetService(serviceType, serviceKey) + ?? (serviceKey is null && serviceType == typeof(AIAgentMetadata) ? this._metadata + : serviceKey is null && serviceType == typeof(AIProjectClient) ? this._aiProjectClient + : serviceKey is null && serviceType == typeof(ChatClientAgent) ? this._innerAgent + : this._innerAgent.GetService(serviceType, serviceKey)); + } + + /// + protected override Task RunCoreAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => this._innerAgent.RunAsync(messages, session, options, cancellationToken); + + /// + protected override IAsyncEnumerable RunCoreStreamingAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => this._innerAgent.RunStreamingAsync(messages, session, options, cancellationToken); + + /// + protected override ValueTask CreateSessionCoreAsync(CancellationToken cancellationToken = default) + => this._innerAgent.CreateSessionAsync(cancellationToken); + + /// + protected override ValueTask SerializeSessionCoreAsync(AgentSession session, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) + => this._innerAgent.SerializeSessionAsync(session, jsonSerializerOptions, cancellationToken); + + /// + protected override ValueTask DeserializeSessionCoreAsync(JsonElement serializedState, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) + => this._innerAgent.DeserializeSessionAsync(serializedState, jsonSerializerOptions, cancellationToken); +} diff --git a/dotnet/src/Microsoft.Agents.AI.AzureAI/RequestOptionsExtensions.cs b/dotnet/src/Microsoft.Agents.AI.AzureAI/RequestOptionsExtensions.cs index 722d316330..2705611b57 100644 --- a/dotnet/src/Microsoft.Agents.AI.AzureAI/RequestOptionsExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.AzureAI/RequestOptionsExtensions.cs @@ -7,6 +7,9 @@ namespace Microsoft.Agents.AI; internal static class RequestOptionsExtensions { + /// Gets the singleton that adds a MEAI user-agent header. + internal static PipelinePolicy UserAgentPolicy => MeaiUserAgentPolicy.Instance; + /// Creates a configured for use with Foundry Agents. public static RequestOptions ToRequestOptions(this CancellationToken cancellationToken, bool streaming) { diff --git a/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProvider.cs b/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProvider.cs index 35baa055d1..87e8d5d582 100644 --- a/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProvider.cs +++ b/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. using System; using System.ClientModel; @@ -18,7 +18,7 @@ namespace Microsoft.Agents.AI.FoundryMemory; /// -/// Provides an Azure AI Foundry Memory backed that persists conversation messages as memories +/// Provides an Microsoft Foundry Memory backed that persists conversation messages as memories /// and retrieves related memories to augment the agent invocation context. /// /// @@ -48,7 +48,7 @@ public sealed class FoundryMemoryProvider : AIContextProvider /// Initializes a new instance of the class. /// /// The Azure AI Project client configured for your Foundry project. - /// The name of the memory store in Azure AI Foundry. + /// The name of the memory store in Microsoft Foundry. /// A delegate that initializes the provider state on the first invocation, providing the scope for memory storage and retrieval. /// Provider options. /// Optional logger factory. @@ -331,7 +331,7 @@ public async Task EnsureMemoryStoreCreatedAsync( /// Waits for all pending memory update operations to complete. /// /// - /// Memory extraction in Azure AI Foundry is asynchronous. This method polls the latest pending update + /// Memory extraction in Microsoft Foundry is asynchronous. This method polls the latest pending update /// and returns when it has completed, failed, or been superseded. Since updates are processed in order, /// completion of the latest update implies all prior updates have also been processed. /// diff --git a/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProviderScope.cs b/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProviderScope.cs index 717df1d12b..b845052029 100644 --- a/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProviderScope.cs +++ b/dotnet/src/Microsoft.Agents.AI.FoundryMemory/FoundryMemoryProviderScope.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. using System; using Microsoft.Shared.Diagnostics; @@ -9,7 +9,7 @@ namespace Microsoft.Agents.AI.FoundryMemory; /// Allows scoping of memories for the . /// /// -/// Azure AI Foundry memories are scoped by a single string identifier that you control. +/// Microsoft Foundry memories are scoped by a single string identifier that you control. /// Common patterns include using a user ID, team ID, or other unique identifier /// to partition memories across different contexts. /// diff --git a/dotnet/tests/AzureAI.IntegrationTests/AIProjectClientAgentStructuredOutputRunTests.cs b/dotnet/tests/AzureAI.IntegrationTests/AIProjectClientAgentStructuredOutputRunTests.cs index 94ce01e221..d2c230a5a0 100644 --- a/dotnet/tests/AzureAI.IntegrationTests/AIProjectClientAgentStructuredOutputRunTests.cs +++ b/dotnet/tests/AzureAI.IntegrationTests/AIProjectClientAgentStructuredOutputRunTests.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Threading.Tasks; using AgentConformance.IntegrationTests; using AgentConformance.IntegrationTests.Support; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/ObjectModel/RequestExternalInputExecutorTest.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/ObjectModel/RequestExternalInputExecutorTest.cs index 778a6dd7b7..7fd79dca18 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/ObjectModel/RequestExternalInputExecutorTest.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/ObjectModel/RequestExternalInputExecutorTest.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks;