-
Notifications
You must be signed in to change notification settings - Fork 845
.NET: Add Anthropic Agent Package #2359
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
rogerbarreto
merged 31 commits into
microsoft:main
from
rogerbarreto:feature-anthropic-dotnet
Nov 25, 2025
Merged
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
962b479
WIP
rogerbarreto a9077ab
WIP
rogerbarreto 179fcce
Simple call working
rogerbarreto c849515
Update Thinking sample
rogerbarreto 6e6e547
Non-Streaming Function calling working
rogerbarreto d44f62c
Update Anthropic Impl
rogerbarreto b1f6466
Public Preps
rogerbarreto 7ed4cae
Merge branch 'main' of https://github.com/microsoft/agent-framework i…
rogerbarreto d22c39e
UT + IT working
rogerbarreto faf8831
Update documentation + samples
rogerbarreto b7d548c
Update variable
rogerbarreto e6004a0
Revert nuget.config
rogerbarreto 66b9fde
Merge branch 'main' into feature-anthropic-dotnet
rogerbarreto ffbaf27
Add IT for BetaService implementation
rogerbarreto df8c3ad
Merge branch 'feature-anthropic-dotnet' of https://github.com/rogerba…
rogerbarreto e804946
Remove polyfill + enable IT to run for netstandard 2.0
rogerbarreto 3096b27
Skipping Anthropic IT's for manual execution and avoid pipeline execu…
rogerbarreto ad5b54b
Fix compilation error
rogerbarreto e7b7a41
Address error in UT
rogerbarreto 762cbb3
Merge branch 'main' into feature-anthropic-dotnet
rogerbarreto 4d9e3eb
Apply suggestions from code review
rogerbarreto 0bffbb4
Merge branch 'main' into feature-anthropic-dotnet
rogerbarreto cb7c83c
Fix warning
rogerbarreto b1ed0e4
Net 10 update
rogerbarreto 18b69bb
Update for NET 10, remove Anthropic.Foundry due to vulnerability
rogerbarreto c9170e4
Final missing adjustments for NET 10
rogerbarreto 2797604
Address PR comments
rogerbarreto 9c4fc46
Remove unused code
rogerbarreto 39aea86
Merge branch 'main' into feature-anthropic-dotnet
rogerbarreto 257ca61
Address feedback
rogerbarreto e11fcfc
Merge branch 'main' into feature-anthropic-dotnet
rogerbarreto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
...et/samples/GettingStarted/AgentProviders/Agent_With_Anthropic/Agent_With_Anthropic.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFrameworks>net10.0</TargetFrameworks> | ||
|
|
||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <NoWarn>$(NoWarn);IDE0059</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Azure.Identity" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Anthropic\Microsoft.Agents.AI.Anthropic.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
101 changes: 101 additions & 0 deletions
101
dotnet/samples/GettingStarted/AgentProviders/Agent_With_Anthropic/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| // This sample shows how to create and use an AI agent with Anthropic as the backend. | ||
|
|
||
| using System.ClientModel; | ||
| using System.Net.Http.Headers; | ||
| using Anthropic; | ||
| using Anthropic.Core; | ||
| using Azure.Core; | ||
| using Azure.Identity; | ||
| using Microsoft.Agents.AI; | ||
| using Sample; | ||
|
|
||
| var deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_DEPLOYMENT_NAME") ?? "claude-haiku-4-5"; | ||
|
|
||
| // The resource is the subdomain name / first name coming before '.services.ai.azure.com' in the endpoint Uri | ||
| // ie: https://(resource name).services.ai.azure.com/anthropic/v1/chat/completions | ||
| var resource = Environment.GetEnvironmentVariable("ANTHROPIC_RESOURCE"); | ||
| var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY"); | ||
|
|
||
| const string JokerInstructions = "You are good at telling jokes."; | ||
| const string JokerName = "JokerAgent"; | ||
|
|
||
| AnthropicClient? client = (resource is null) | ||
| ? new AnthropicClient() { APIKey = apiKey ?? throw new InvalidOperationException("ANTHROPIC_API_KEY is required when no ANTHROPIC_RESOURCE is provided") } // If no resource is provided, use Anthropic public API | ||
| : (apiKey is not null) | ||
| ? new AnthropicFoundryClient(resource, new ApiKeyCredential(apiKey)) // If an apiKey is provided, use Foundry with ApiKey authentication | ||
| : new AnthropicFoundryClient(resource, new AzureCliCredential()); // Otherwise, use Foundry with Azure Client authentication | ||
|
|
||
| AIAgent agent = client.CreateAIAgent(model: deploymentName, instructions: JokerInstructions, name: JokerName); | ||
rogerbarreto marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Invoke the agent and output the text result. | ||
| Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.")); | ||
|
|
||
| namespace Sample | ||
| { | ||
| /// <summary> | ||
| /// Provides methods for invoking the Azure hosted Anthropic api. | ||
| /// </summary> | ||
| public class AnthropicFoundryClient : AnthropicClient | ||
| { | ||
| private readonly TokenCredential _tokenCredential; | ||
| private readonly string _resourceName; | ||
|
|
||
| /// <summary> | ||
| /// Creates a new instance of the <see cref="AnthropicFoundryClient"/>. | ||
| /// </summary> | ||
| /// <param name="resourceName">The service resource subdomain name to use in the anthropic azure endpoint</param> | ||
| /// <param name="tokenCredential">The credential provider. Use any specialization of <see cref="TokenCredential"/> to get your access token in supported environments.</param> | ||
| /// <param name="options">Set of <see cref="Anthropic.Core.ClientOptions"/> client option configurations</param> | ||
| /// <exception cref="ArgumentNullException">Resource is null</exception> | ||
| /// <exception cref="ArgumentNullException">TokenCredential is null</exception> | ||
| /// <remarks> | ||
| /// Any <see cref="Anthropic.Core.ClientOptions"/> APIKey or Bearer token provided will be ignored in favor of the <see cref="TokenCredential"/> provided in the constructor | ||
| /// </remarks> | ||
| public AnthropicFoundryClient(string resourceName, TokenCredential tokenCredential, Anthropic.Core.ClientOptions? options = null) : base(options ?? new()) | ||
| { | ||
| this._resourceName = resourceName ?? throw new ArgumentNullException(nameof(resourceName)); | ||
| this._tokenCredential = tokenCredential ?? throw new ArgumentNullException(nameof(tokenCredential)); | ||
| this.BaseUrl = new Uri($"https://{this._resourceName}.services.ai.azure.com/anthropic", UriKind.Absolute); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates a new instance of the <see cref="AnthropicFoundryClient"/>. | ||
| /// </summary> | ||
| /// <param name="resourceName">The service resource subdomain name to use in the anthropic azure endpoint</param> | ||
| /// <param name="apiKeyCredential">The api key.</param> | ||
| /// <param name="options">Set of <see cref="Anthropic.Core.ClientOptions"/> client option configurations</param> | ||
| /// <exception cref="ArgumentNullException">Resource is null</exception> | ||
| /// <exception cref="ArgumentNullException">Api key is null</exception> | ||
| /// <remarks> | ||
| /// Any <see cref="Anthropic.Core.ClientOptions"/> APIKey or Bearer token provided will be ignored in favor of the <see cref="ApiKeyCredential"/> provided in the constructor | ||
| /// </remarks> | ||
| public AnthropicFoundryClient(string resourceName, ApiKeyCredential apiKeyCredential, Anthropic.Core.ClientOptions? options = null) : | ||
| this(resourceName, apiKeyCredential is null | ||
| ? throw new ArgumentNullException(nameof(apiKeyCredential)) | ||
| : DelegatedTokenCredential.Create((_, _) => | ||
| { | ||
| apiKeyCredential.Deconstruct(out string dangerousCredential); | ||
| return new AccessToken(dangerousCredential, DateTimeOffset.MaxValue); | ||
| }), | ||
| options) | ||
| { } | ||
|
|
||
| public override IAnthropicClient WithOptions(Func<Anthropic.Core.ClientOptions, Anthropic.Core.ClientOptions> modifier) | ||
| => this; | ||
|
|
||
| protected override ValueTask BeforeSend<T>( | ||
| HttpRequest<T> request, | ||
| HttpRequestMessage requestMessage, | ||
| CancellationToken cancellationToken | ||
| ) | ||
| { | ||
| var accessToken = this._tokenCredential.GetToken(new TokenRequestContext(scopes: ["https://ai.azure.com/.default"]), cancellationToken); | ||
|
|
||
| requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken.Token); | ||
|
|
||
| return default; | ||
| } | ||
| } | ||
| } | ||
53 changes: 53 additions & 0 deletions
53
dotnet/samples/GettingStarted/AgentProviders/Agent_With_Anthropic/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| # Creating an AIAgent with Anthropic | ||
|
|
||
| This sample demonstrates how to create an AIAgent using Anthropic Claude models as the underlying inference service. | ||
|
|
||
| The sample supports three deployment scenarios: | ||
|
|
||
| 1. **Anthropic Public API** - Direct connection to Anthropic's public API | ||
| 2. **Azure Foundry with API Key** - Anthropic models deployed through Azure Foundry using API key authentication | ||
| 3. **Azure Foundry with Azure CLI** - Anthropic models deployed through Azure Foundry using Azure CLI credentials | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| Before you begin, ensure you have the following prerequisites: | ||
|
|
||
| - .NET 8.0 SDK or later | ||
|
|
||
| ### For Anthropic Public API | ||
|
|
||
| - Anthropic API key | ||
|
|
||
| Set the following environment variables: | ||
|
|
||
| ```powershell | ||
| $env:ANTHROPIC_API_KEY="your-anthropic-api-key" # Replace with your Anthropic API key | ||
| $env:ANTHROPIC_DEPLOYMENT_NAME="claude-haiku-4-5" # Optional, defaults to claude-haiku-4-5 | ||
| ``` | ||
|
|
||
| ### For Azure Foundry with API Key | ||
|
|
||
| - Azure Foundry service endpoint and deployment configured | ||
| - Anthropic API key | ||
|
|
||
| Set the following environment variables: | ||
|
|
||
| ```powershell | ||
| $env:ANTHROPIC_RESOURCE="your-foundry-resource-name" # Replace with your Azure Foundry resource name (subdomain before .services.ai.azure.com) | ||
| $env:ANTHROPIC_API_KEY="your-anthropic-api-key" # Replace with your Anthropic API key | ||
| $env:ANTHROPIC_DEPLOYMENT_NAME="claude-haiku-4-5" # Optional, defaults to claude-haiku-4-5 | ||
| ``` | ||
|
|
||
| ### For Azure Foundry with Azure CLI | ||
|
|
||
| - Azure Foundry service endpoint and deployment configured | ||
| - Azure CLI installed and authenticated (for Azure credential authentication) | ||
|
|
||
| Set the following environment variables: | ||
|
|
||
| ```powershell | ||
| $env:ANTHROPIC_RESOURCE="your-foundry-resource-name" # Replace with your Azure Foundry resource name (subdomain before .services.ai.azure.com) | ||
| $env:ANTHROPIC_DEPLOYMENT_NAME="claude-haiku-4-5" # Optional, defaults to claude-haiku-4-5 | ||
| ``` | ||
|
|
||
| **Note**: When using Azure Foundry with Azure CLI, 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). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
...d/AgentWithAnthropic/Agent_Anthropic_Step01_Running/Agent_Anthropic_Step01_Running.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
|
|
||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Anthropic\Microsoft.Agents.AI.Anthropic.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
24 changes: 24 additions & 0 deletions
24
dotnet/samples/GettingStarted/AgentWithAnthropic/Agent_Anthropic_Step01_Running/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| // This sample shows how to create and use a simple AI agent with Anthropic as the backend. | ||
|
|
||
| using Anthropic; | ||
| using Anthropic.Core; | ||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Extensions.AI; | ||
|
|
||
| var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY") ?? throw new InvalidOperationException("ANTHROPIC_API_KEY is not set."); | ||
| var model = Environment.GetEnvironmentVariable("ANTHROPIC_MODEL") ?? "claude-haiku-4-5"; | ||
|
|
||
| AIAgent agent = new AnthropicClient(new ClientOptions { APIKey = apiKey }) | ||
| .CreateAIAgent(model: model, instructions: "You are good at telling jokes.", name: "Joker"); | ||
|
|
||
| // Invoke the agent and output the text result. | ||
| var response = await agent.RunAsync("Tell me a joke about a pirate."); | ||
| Console.WriteLine(response); | ||
|
|
||
| // Invoke the agent with streaming support. | ||
| await foreach (var update in agent.RunStreamingAsync("Tell me a joke about a pirate.")) | ||
| { | ||
| Console.WriteLine(update); | ||
| } |
43 changes: 43 additions & 0 deletions
43
...ples/GettingStarted/AgentWithAnthropic/Agent_Anthropic_Step01_Running/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Running a simple agent with Anthropic | ||
|
|
||
| This sample demonstrates how to create and run a basic agent with Anthropic Claude models. | ||
|
|
||
| ## What this sample demonstrates | ||
|
|
||
| - Creating an AI agent with Anthropic Claude | ||
| - Running a simple agent with instructions | ||
| - Managing agent lifecycle | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| Before you begin, ensure you have the following prerequisites: | ||
|
|
||
| - .NET 8.0 SDK or later | ||
| - Anthropic API key configured | ||
|
|
||
| **Note**: This sample uses Anthropic Claude models. For more information, see [Anthropic documentation](https://docs.anthropic.com/). | ||
|
|
||
| Set the following environment variables: | ||
|
|
||
| ```powershell | ||
| $env:ANTHROPIC_API_KEY="your-anthropic-api-key" # Replace with your Anthropic API key | ||
rogerbarreto marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| $env:ANTHROPIC_MODEL="your-anthropic-model" # Replace with your Anthropic model | ||
| ``` | ||
|
|
||
| ## Run the sample | ||
|
|
||
| Navigate to the AgentWithAnthropic sample directory and run: | ||
|
|
||
| ```powershell | ||
| cd dotnet\samples\GettingStarted\AgentWithAnthropic | ||
| dotnet run --project .\Agent_Anthropic_Step01_Running | ||
| ``` | ||
|
|
||
| ## Expected behavior | ||
|
|
||
| The sample will: | ||
|
|
||
| 1. Create an agent with Anthropic Claude | ||
| 2. Run the agent with a simple prompt | ||
| 3. Display the agent's response | ||
|
|
||
15 changes: 15 additions & 0 deletions
15
...entWithAnthropic/Agent_Anthropic_Step02_Reasoning/Agent_Anthropic_Step02_Reasoning.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
|
|
||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Anthropic\Microsoft.Agents.AI.Anthropic.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.