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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ $env:AZURE_TOKEN_CREDENTIALS = "AzureDeveloperCliCredential"
python src/hello_claude.py # one-shot Messages call (Entra ID)
python src/chat_stream.py # interactive streaming chat — type a message, `exit` to quit
python src/hello_claude_token_refresh.py # long-running variant with per-request token refresh
python src/message_threads.py # two-turn Message Threads beta
```

<details>
Expand Down Expand Up @@ -239,7 +240,7 @@ The standard client does not consume `ANTHROPIC_FOUNDRY_RESOURCE`. The explicit

A captured static token eventually expires. [src/hello_claude_token_refresh.py](./src/hello_claude_token_refresh.py) uses a cached bearer-token callback instead. The standard SDK's request hook asks for the current token on every request and retry; Azure Identity caches and renews it. There is no custom token cache, retry loop, SDK subclass, or automatic native OAuth beta header.

[requirements.txt](./requirements.txt) targets Anthropic SDK **2.1+** and Azure Identity **1.26+**, with upper bounds at the next major version. SDK 2.x uses `httpx2` for custom transports; it is not interchangeable with `httpx`.
[requirements.txt](./requirements.txt) targets Anthropic SDK **2.4+** and Azure Identity **1.26+**, with upper bounds at the next major version. SDK 2.x uses `httpx2` for custom transports; it is not interchangeable with `httpx`.

</details>

Expand All @@ -249,7 +250,7 @@ A captured static token eventually expires. [src/hello_claude_token_refresh.py](

| Language | Sample and instructions |
|---|---|
| Python | [One-shot](./src/hello_claude.py), [streaming](./src/chat_stream.py), [token refresh](./src/hello_claude_token_refresh.py) |
| Python | [One-shot](./src/hello_claude.py), [streaming](./src/chat_stream.py), [token refresh](./src/hello_claude_token_refresh.py), [threads](./src/message_threads.py) |
| TypeScript | [samples/typescript](./samples/typescript/README.md) |
| C# | [samples/dotnet](./samples/dotnet/README.md) |
| Go | [samples/go](./samples/go/README.md) |
Expand All @@ -259,6 +260,8 @@ A captured static token eventually expires. [src/hello_claude_token_refresh.py](

Helpers return ordinary SDK clients; application code still calls the usual Messages and streaming APIs. [Shared configuration](./samples/README.md) selects the endpoint, model, authentication, key header and API version. The same samples can target Anthropic's native endpoint without changing imports or inference code.

Separate [Message Threads examples](./samples/message-threads.md) opt into `anthropic-beta: message-threads-2026-08-12`. The guide includes SDK requirements and live Foundry compatibility checks.

Python, TypeScript, C#, Go and Java use their official Azure Identity SDKs. PHP and Ruby accept a token-provider callback and use Azure CLI as a documented local fallback; this is **not** an official Azure Identity SDK for those languages.

Claude Code's built-in Foundry mode below is independent of these SDK samples and remains unchanged.
Expand Down Expand Up @@ -547,6 +550,7 @@ claude/
│ ├── hello_claude_apikey.py # Same, but with an API key (dev/test only)
│ ├── hello_claude_token_refresh.py # Long-running variant with auto-refreshing Entra token
│ ├── chat_stream.py # Streaming multi-turn chat loop
│ ├── message_threads.py # Two-turn Message Threads beta
│ └── check_claude_quota.py # Inspect Claude quota + capacity via ARM (see Advanced)
├── Get-ClaudeCatalog.ps1
├── requirements.txt
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
anthropic>=2.1.0,<3
anthropic>=2.4.0,<3
azure-identity>=1.26.0,<2
azure-core>=1.41.0,<2
python-dotenv>=1.2.4,<2
Expand Down
6 changes: 5 additions & 1 deletion samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ Each language uses its standard Anthropic SDK client. Generic client/authenticat

PHP/Ruby's CLI fallback is explicit because no current official Azure Identity SDK was identified for those languages. It is not a production managed-identity implementation. Supply an appropriate renewable-token callback in hosted applications.

## Message Threads

The separate [Threads examples](message-threads.md) send only the new turn after creating a conversation. They opt into `anthropic-beta: message-threads-2026-08-12`; the existing Messages and streaming examples do not. See the guide for run commands, SDK requirements and Foundry API findings.

## Configuration

Python loads the gitignored root `.env.local`; the other entrypoints read process environment variables. Export the selected `azd` environment before running them. Never put real keys, tokens, tenant IDs or subscription IDs in checked-in configuration.
Expand Down Expand Up @@ -77,7 +81,7 @@ Cloud provisioning remains the existing `azd up` workflow in one selected IaC va

The migration was live-tested against a freshly provisioned Haiku 5.5 version 2 deployment in `eastus2`: all seven languages passed Messages, SSE streaming and resource-key authentication with native SDK defaults. Python, TypeScript, C#, Go and Java also passed a configuration-only switch between Azure CLI and Azure Developer CLI credentials. Native Anthropic endpoint routing is covered by offline recording transports; no native-account live test is claimed.

The TypeScript sample is pinned to the tested SDK 1.1.0 because the configured package feed did not provide 1.3.0 and direct public-registry access failed TLS negotiation in the test environment. Relevant 1.3.0 source was compared, but that package version was not executed. Other runtime/version details are in the language READMEs.
TypeScript now pins SDK 1.4.0 for Threads; its Messages, streaming and Threads paths also passed live bearer runs. Other runtime/version details are in the language READMEs.

## Upstream requests

Expand Down
14 changes: 13 additions & 1 deletion samples/dotnet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ There is no `Anthropic.Foundry` package, client subclass, alternate Messages API
| `src/AnthropicStandardSdk/ClientFactory.cs` | Generic helper. Builds the standard client with one explicit credential. Knows no identity library and reads no environment. Copy this one file (it needs only the `Anthropic` package). |
| `src/AnthropicStandardSdk/CredentialSelector.cs` | The only code that uses Azure Identity: selects one credential class and adapts it to the helper's `TokenProvider` callback. |
| `src/AnthropicStandardSdk/SampleSettings.cs`, `SampleRunner.cs`, `Program.cs` | Environment parsing, the Messages/streaming calls, output and exit codes. |
| `src/AnthropicStandardSdk/ThreadsExample.cs` | The `--threads` message-thread example. Same settings, factory and credentials; no extra project. |
| `tests/AnthropicStandardSdk.Tests` | Offline tests: the real SDK against recording transports and loopback servers. |

## Run
Expand Down Expand Up @@ -38,6 +39,17 @@ or usage error. Each call uses `max_tokens` 1024 and a 120 second per-call timeo
policy, set explicitly in `SampleRunner`; `ClientFactory` keeps the SDK's timeout unless the caller sets `Timeout`.
The SDK's default retries and cancellation behavior are unchanged.

## Message threads

`--threads` runs the separate example in `ThreadsExample.cs` with the same configuration and client:

```powershell
dotnet run --project samples/dotnet/src/AnthropicStandardSdk -- --threads
```

It prints the second reply and fails if there is no text. It takes no prompt and cannot be combined with `--stream`.
The SDK helper adds `anthropic-beta: message-threads-2026-08-12` and handles replay. See the [Threads guide](../message-threads.md).

## Configuration

Read by the sample entrypoint only (never by `ClientFactory`). Real keys and IDs belong in the environment or a
Expand Down Expand Up @@ -124,4 +136,4 @@ dotnet test samples/dotnet/AnthropicStandardSdk.sln
not the retries.
- `AzureCliCredential` and `AzureDeveloperCliCredential` need their CLI on `PATH`; use `ManagedIdentityCredential` in
hosted environments.
- Only the Messages and streaming calls are demonstrated. Other SDK APIs go through the same client and handler.
- Only the Messages, streaming and message-thread calls are demonstrated. Other SDK APIs go through the same client and handler.
25 changes: 22 additions & 3 deletions samples/dotnet/src/AnthropicStandardSdk/SampleRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,14 @@ internal static class SampleRunner
internal static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(120);

private const string DefaultPrompt = "Say hello in one short sentence.";
private const string UsageText = "usage: AnthropicStandardSdk [--stream] [prompt...]";
private const string UsageText = "usage: AnthropicStandardSdk [--stream] [prompt...] | --threads";

private static readonly Regex Whitespace = new Regex(@"\s+", RegexOptions.Compiled);

/// <summary>
/// Runs one Messages call (or one streaming call with <c>--stream</c>). Environment access,
/// credential creation and the HTTP transport are parameters so tests can supply recording fakes.
/// Runs one Messages call, one streaming call with <c>--stream</c>, or the message-thread example with
/// <c>--threads</c>. Environment access, credential creation and the HTTP transport are parameters so
/// tests can supply recording fakes.
/// </summary>
public static async Task<int> RunAsync(
string[] args,
Expand All @@ -52,6 +53,7 @@ public static async Task<int> RunAsync(
Func<SampleSettings, TokenCredential>? credentialFactory = null)
{
bool stream = false;
bool threads = false;
bool optionsEnded = false;
List<string> promptWords = new List<string>();
foreach (string arg in args)
Expand All @@ -64,6 +66,10 @@ public static async Task<int> RunAsync(
{
stream = true;
}
else if (!optionsEnded && arg == "--threads")
{
threads = true;
}
else if (!optionsEnded && (arg == "-h" || arg == "--help"))
{
output.WriteLine(UsageText);
Expand All @@ -81,6 +87,13 @@ public static async Task<int> RunAsync(
}
}

if (threads && (stream || promptWords.Count > 0))
{
error.WriteLine("error: --threads takes no prompt and cannot be combined with --stream");
error.WriteLine(UsageText);
return ExitUsage;
}

string prompt = promptWords.Count > 0 ? string.Join(" ", promptWords) : DefaultPrompt;

SampleSettings settings;
Expand Down Expand Up @@ -139,6 +152,12 @@ public static async Task<int> RunAsync(

using (client)
{
if (threads)
{
await ThreadsExample.RunAsync(client, settings.Model, output, cancellationToken).ConfigureAwait(false);
return ExitOk;
}

MessageCreateParams parameters = new MessageCreateParams
{
Model = settings.Model,
Expand Down
60 changes: 60 additions & 0 deletions samples/dotnet/src/AnthropicStandardSdk/ThreadsExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Anthropic;
using Anthropic.Helpers.Beta;
using Anthropic.Models.Beta.Messages;

namespace AnthropicStandardSdk;

/// <summary>Message threads (beta), run with <c>--threads</c>: the second turn sends only its new message.</summary>
internal static class ThreadsExample
{
private const string FirstPrompt = "Remember the code ORCHID-47. Reply with OK.";
private const string SecondPrompt = "What code did I ask you to remember? Reply with only the code.";
private const string SystemPrompt = "Keep replies short.";
private const long MaxTokens = 1024;

public static async Task RunAsync(
AnthropicClient client, string model, TextWriter output, CancellationToken cancellationToken)
{
BetaMessageThread thread = client.Beta.Messages.Thread(new ThreadCreateParams
{
Model = model,
MaxTokens = MaxTokens,
System = SystemPrompt,
Messages = [],
});

await thread.Send(new BetaUserMessageParam { Content = FirstPrompt }, cancellationToken).ConfigureAwait(false);
BetaMessage second = await thread
.Send(new BetaUserMessageParam { Content = SecondPrompt }, cancellationToken)
.ConfigureAwait(false);

output.WriteLine(TextOf(second));
}

private static string TextOf(BetaMessage message)
{
StringBuilder text = new StringBuilder();
List<string> blockKinds = new List<string>();
foreach (BetaContentBlock block in message.Content)
{
blockKinds.Add(block.Value?.GetType().Name ?? "unknown");
if (block.TryPickText(out BetaTextBlock? textBlock))
{
text.Append(textBlock.Text);
}
}

if (string.IsNullOrWhiteSpace(text.ToString()))
{
throw new UnusableResponseException(
"The response contained no text (content blocks: " + string.Join(", ", blockKinds) + ").");
}

return text.ToString();
}
}
Loading
Loading