-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathapp.cs
More file actions
582 lines (495 loc) · 19.3 KB
/
app.cs
File metadata and controls
582 lines (495 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#:package Azure.AI.OpenAI@2.8.0-beta.1
#:package Azure.Identity@1.18.0
#:package Microsoft.Extensions.AI@10.3.0
#:package Microsoft.Extensions.AI.OpenAI@10.3.0
#:package Microsoft.Extensions.Configuration.UserSecrets@10.0.3
#:property UserSecretsId=genai-beginners-dotnet
using Azure.AI.OpenAI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Text;
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
var endpoint = config["AzureOpenAI:Endpoint"]
?? throw new InvalidOperationException("Set AzureOpenAI:Endpoint in User Secrets. See: https://github.com/microsoft/Generative-AI-for-beginners-dotnet/blob/main/01-IntroductionToGenerativeAI/setup-azure-openai.md");
var endpointClaude = config["Claude:Endpoint"]
?? throw new InvalidOperationException("Set Claude:Endpoint in User Secrets.");
var apiKey = config["AzureOpenAI:ApiKey"]
?? throw new InvalidOperationException("Set AzureOpenAI:ApiKey in User Secrets. See: https://github.com/microsoft/Generative-AI-for-beginners-dotnet/blob/main/01-IntroductionToGenerativeAI/setup-azure-openai.md");
var deploymentName = config["Claude:Deployment"]
?? throw new InvalidOperationException("Set Claude:Deployment in User Secrets.");
// 1. create custom http client that will handle Claude endpoint in Azure
var customHttpMessageHandler = new ClaudeToOpenAIMessageHandler
{
AzureClaudeDeploymentUrl = endpointClaude,
ApiKey = apiKey, // Pass the API key to the handler
Model = deploymentName // Pass the model name to the handler
};
HttpClient customHttpClient = new(customHttpMessageHandler);
// 2. Wrap HttpClient in the NEW pipeline transport
var transport = new HttpClientPipelineTransport(customHttpClient);
// 3. Client options (generational)
var clientOptions = new AzureOpenAIClientOptions
{
Transport = transport
};
// 4. Credential type for generational client
var apiKeyCredential = new ApiKeyCredential(apiKey);
// 5. Create the client with the custom transport and credential
IChatClient client = new AzureOpenAIClient(
endpoint: new Uri(endpoint),
credential: apiKeyCredential,
options: clientOptions)
.GetChatClient(deploymentName)
.AsIChatClient()
.AsBuilder()
.Build();
var history = new List<ChatMessage>
{
new(ChatRole.System, "You are a useful chatbot.")
};
while (true)
{
Console.Write("Q: ");
var userQ = Console.ReadLine();
if (string.IsNullOrEmpty(userQ))
{
break;
}
history.Add(new ChatMessage(ChatRole.User, userQ));
var sb = new StringBuilder();
var result = client.GetStreamingResponseAsync(history);
Console.Write($"AI [{deploymentName}]: ");
await foreach (var item in result)
{
// validate if the item is null or has no contents
if (item == null || item.Contents.Count == 0)
{
continue; // skip to the next item if it's null or empty
}
sb.Append(item);
Console.Write(item.Contents[0].ToString());
}
Console.WriteLine();
history.Add(new ChatMessage(ChatRole.Assistant, sb.ToString()));
}
using System.Text.Json;
using System.Text.Json.Nodes;
/// <summary>
/// HTTP message handler that transforms requests/responses between OpenAI format and Claude (Anthropic) format
/// for Microsoft Foundry deployments.
/// </summary>
public class ClaudeToOpenAIMessageHandler : DelegatingHandler
{
// Constants for better maintainability
private const string ClaudeAnthropicVersion = "2023-06-01";
private const string ClaudeEventTypeContentDelta = "content_block_delta";
private const string ClaudeEventTypeMessageStop = "message_stop";
private const string OpenAIStreamDoneMarker = "[DONE]";
private const int DefaultMaxTokens = 2048;
private const string DefaultModelName = "claude-haiku-4-5";
// Deployment URL patterns to detect Claude requests
private static readonly string[] ClaudeDeploymentPatterns = {
"deployments/claude-haiku",
"deployments/claude-sonnet",
"deployments/claude-opus"
};
/// <summary>
/// Gets or sets the Azure Claude deployment URL endpoint.
/// Format: https://{resource-name}.services.ai.azure.com/anthropic/v1/messages
/// </summary>
public required string AzureClaudeDeploymentUrl { get; set; }
/// <summary>
/// Gets or sets the API key for authenticating with Claude in Microsoft Foundry.
/// </summary>
public required string ApiKey { get; set; }
/// <summary>
/// Gets or sets the Claude model name (e.g., "claude-haiku-4-5", "claude-sonnet-4-5").
/// </summary>
public required string Model { get; set; }
public ClaudeToOpenAIMessageHandler() : base(new HttpClientHandler())
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isClaudeRequest = IsClaudeRequest(request);
if (isClaudeRequest)
{
await TransformRequestToClaude(request, cancellationToken);
request.RequestUri = new Uri(AzureClaudeDeploymentUrl);
}
var response = await base.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode)
{
await LogErrorResponse(response, cancellationToken);
}
if (isClaudeRequest)
{
response = await TransformResponseToOpenAI(response, cancellationToken);
}
return response;
}
private bool IsClaudeRequest(HttpRequestMessage request)
{
return request.RequestUri != null &&
ClaudeDeploymentPatterns.Any(pattern => request.RequestUri.AbsoluteUri.Contains(pattern));
}
private async Task LogErrorResponse(HttpResponseMessage response, CancellationToken cancellationToken)
{
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
Console.WriteLine($"[ERROR] {response.StatusCode}: {errorBody}");
}
#region Request Transformation
private async Task TransformRequestToClaude(HttpRequestMessage request, CancellationToken cancellationToken)
{
var openAIJson = await ReadOpenAIRequestBody(request, cancellationToken);
var (claudeMessages, systemMessage) = ConvertMessagesToClaudeFormat(openAIJson);
var claudeBody = BuildClaudeRequestBody(openAIJson, claudeMessages, systemMessage);
ConfigureClaudeRequestHeaders(request);
request.Content = new StringContent(claudeBody.ToJsonString(), Encoding.UTF8, "application/json");
}
private async Task<JsonNode> ReadOpenAIRequestBody(HttpRequestMessage request, CancellationToken cancellationToken)
{
var openAIBody = await request.Content!.ReadAsStringAsync(cancellationToken);
return JsonNode.Parse(openAIBody)!;
}
private (JsonArray messages, string? systemMessage) ConvertMessagesToClaudeFormat(JsonNode openAIJson)
{
var messages = openAIJson["messages"]?.AsArray();
var claudeMessages = new JsonArray();
string? systemMessage = null;
if (messages != null)
{
foreach (var msg in messages)
{
ProcessMessage(msg!, claudeMessages, ref systemMessage);
}
}
return (claudeMessages, systemMessage);
}
private void ProcessMessage(JsonNode msg, JsonArray claudeMessages, ref string? systemMessage)
{
var role = msg["role"]?.ToString();
var content = msg["content"]?.ToString() ?? "";
if (ShouldExtractAsSystemMessage(role, claudeMessages))
{
systemMessage = content;
return;
}
if (ShouldSkipMessage(content))
{
return;
}
claudeMessages.Add(CreateClaudeMessage(role, content));
}
private bool ShouldExtractAsSystemMessage(string? role, JsonArray claudeMessages)
{
// Extract system messages or initial assistant messages as system prompts
return role == "system" || (role == "assistant" && claudeMessages.Count == 0);
}
private bool ShouldSkipMessage(string content)
{
// Claude requires non-empty content
return string.IsNullOrWhiteSpace(content);
}
private JsonObject CreateClaudeMessage(string? role, string content)
{
return new JsonObject
{
["role"] = role == "assistant" ? "assistant" : "user",
["content"] = content
};
}
private JsonObject BuildClaudeRequestBody(JsonNode openAIJson, JsonArray claudeMessages, string? systemMessage)
{
var claudeBody = new JsonObject
{
["model"] = Model ?? DefaultModelName,
["messages"] = claudeMessages,
["max_tokens"] = openAIJson["max_tokens"]?.GetValue<int>() ?? DefaultMaxTokens,
["stream"] = openAIJson["stream"]?.GetValue<bool>() ?? false
};
if (!string.IsNullOrEmpty(systemMessage))
{
claudeBody["system"] = systemMessage;
}
if (openAIJson["temperature"] != null)
{
claudeBody["temperature"] = openAIJson["temperature"]!.GetValue<double>();
}
// Claude thinking parameter (disabled by default)
claudeBody["thinking"] = new JsonObject { ["type"] = "disabled" };
return claudeBody;
}
private void ConfigureClaudeRequestHeaders(HttpRequestMessage request)
{
RemoveOpenAIAuthHeaders(request);
AddClaudeAuthHeaders(request);
}
private void RemoveOpenAIAuthHeaders(HttpRequestMessage request)
{
request.Headers.Remove("api-key");
request.Headers.Remove("Authorization");
if (request.Content?.Headers != null)
{
var headersToRemove = request.Content.Headers
.Where(h => h.Key.Equals("api-key", StringComparison.OrdinalIgnoreCase) ||
h.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var header in headersToRemove)
{
request.Content.Headers.Remove(header.Key);
}
}
}
private void AddClaudeAuthHeaders(HttpRequestMessage request)
{
// Claude in Microsoft Foundry uses x-api-key header (not Authorization: Bearer)
// See: https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/how-to/use-foundry-models-claude
if (!string.IsNullOrEmpty(ApiKey))
{
request.Headers.TryAddWithoutValidation("x-api-key", ApiKey);
}
else
{
Console.WriteLine("[ERROR] ApiKey is null or empty!");
}
request.Headers.TryAddWithoutValidation("anthropic-version", ClaudeAnthropicVersion);
}
#endregion
#region Response Transformation
private async Task<HttpResponseMessage> TransformResponseToOpenAI(HttpResponseMessage response, CancellationToken cancellationToken)
{
if (!response.IsSuccessStatusCode)
{
return response;
}
var contentType = response.Content.Headers.ContentType?.MediaType;
if (contentType == "text/event-stream")
{
return await TransformStreamingResponse(response, cancellationToken);
}
return await TransformNonStreamingResponse(response, cancellationToken);
}
private async Task<HttpResponseMessage> TransformNonStreamingResponse(HttpResponseMessage response, CancellationToken cancellationToken)
{
var claudeBody = await response.Content.ReadAsStringAsync(cancellationToken);
var claudeJson = JsonNode.Parse(claudeBody);
var openAIResponse = new JsonObject
{
["id"] = claudeJson!["id"]?.ToString() ?? Guid.NewGuid().ToString(),
["object"] = "chat.completion",
["created"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
["model"] = DefaultModelName,
["choices"] = new JsonArray
{
new JsonObject
{
["index"] = 0,
["message"] = new JsonObject
{
["role"] = "assistant",
["content"] = ExtractClaudeContent(claudeJson["content"])
},
["finish_reason"] = claudeJson["stop_reason"]?.ToString() ?? "stop"
}
}
};
return new HttpResponseMessage(response.StatusCode)
{
Content = new StringContent(openAIResponse.ToJsonString(), Encoding.UTF8, "application/json")
};
}
private string ExtractClaudeContent(JsonNode? contentNode)
{
if (contentNode is JsonArray contentArray && contentArray.Count > 0)
{
var firstContent = contentArray[0];
if (firstContent?["type"]?.ToString() == "text")
{
return firstContent["text"]?.ToString() ?? "";
}
}
return contentNode?.ToString() ?? "";
}
#endregion
#region Streaming Response Transformation
private async Task<HttpResponseMessage> TransformStreamingResponse(HttpResponseMessage response, CancellationToken cancellationToken)
{
var originalStream = await response.Content.ReadAsStreamAsync(cancellationToken);
var transformedStream = CreateTransformedStreamPipeline();
StartStreamTransformationTask(originalStream, transformedStream, cancellationToken);
return CreateStreamingResponse(response, transformedStream);
}
private System.IO.Pipelines.Pipe CreateTransformedStreamPipeline()
{
return new System.IO.Pipelines.Pipe();
}
private void StartStreamTransformationTask(
Stream originalStream,
System.IO.Pipelines.Pipe pipeStream,
CancellationToken cancellationToken)
{
_ = Task.Run(async () =>
{
await TransformClaudeStreamToOpenAI(originalStream, pipeStream.Writer, cancellationToken);
}, cancellationToken);
}
private async Task TransformClaudeStreamToOpenAI(
Stream originalStream,
System.IO.Pipelines.PipeWriter writer,
CancellationToken cancellationToken)
{
try
{
using var reader = new StreamReader(originalStream, Encoding.UTF8);
await ProcessClaudeSseEvents(reader, writer, cancellationToken);
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Streaming error: {ex.Message}");
}
finally
{
await writer.CompleteAsync();
}
}
private async Task ProcessClaudeSseEvents(
StreamReader reader,
System.IO.Pipelines.PipeWriter writer,
CancellationToken cancellationToken)
{
string? line;
while ((line = await reader.ReadLineAsync(cancellationToken)) != null)
{
if (line.StartsWith("data: "))
{
await ProcessClaudeDataEvent(line, writer, cancellationToken);
}
}
}
private async Task ProcessClaudeDataEvent(
string line,
System.IO.Pipelines.PipeWriter writer,
CancellationToken cancellationToken)
{
var jsonData = line.Substring(6).Trim();
if (ShouldSkipDataEvent(jsonData))
{
return;
}
try
{
var claudeEvent = JsonNode.Parse(jsonData);
var eventType = claudeEvent?["type"]?.ToString();
await TransformAndWriteEvent(eventType, claudeEvent, writer, cancellationToken);
}
catch (JsonException)
{
// Skip malformed JSON silently
}
}
private bool ShouldSkipDataEvent(string jsonData)
{
return string.IsNullOrWhiteSpace(jsonData) || jsonData == OpenAIStreamDoneMarker;
}
private async Task TransformAndWriteEvent(
string? eventType,
JsonNode? claudeEvent,
System.IO.Pipelines.PipeWriter writer,
CancellationToken cancellationToken)
{
switch (eventType)
{
case ClaudeEventTypeContentDelta:
await WriteContentDeltaChunk(claudeEvent, writer, cancellationToken);
break;
case ClaudeEventTypeMessageStop:
await WriteFinalChunk(writer, cancellationToken);
break;
}
}
private async Task WriteContentDeltaChunk(
JsonNode? claudeEvent,
System.IO.Pipelines.PipeWriter writer,
CancellationToken cancellationToken)
{
var text = ExtractDeltaText(claudeEvent);
if (string.IsNullOrEmpty(text))
{
return;
}
var openAIChunk = CreateOpenAIStreamingChunk(claudeEvent, text, finishReason: null);
await WriteChunkToStream(openAIChunk, writer, cancellationToken);
}
private string? ExtractDeltaText(JsonNode? claudeEvent)
{
return claudeEvent?["delta"]?["text"]?.ToString();
}
private JsonObject CreateOpenAIStreamingChunk(JsonNode? claudeEvent, string text, string? finishReason)
{
return new JsonObject
{
["id"] = claudeEvent?["message_id"]?.ToString() ?? Guid.NewGuid().ToString(),
["object"] = "chat.completion.chunk",
["created"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
["model"] = DefaultModelName,
["choices"] = new JsonArray
{
new JsonObject
{
["index"] = 0,
["delta"] = new JsonObject { ["content"] = text },
["finish_reason"] = JsonValue.Create(finishReason)
}
}
};
}
private async Task WriteChunkToStream(
JsonObject chunk,
System.IO.Pipelines.PipeWriter writer,
CancellationToken cancellationToken)
{
var chunkData = $"data: {chunk.ToJsonString()}\n\n";
await writer.WriteAsync(Encoding.UTF8.GetBytes(chunkData), cancellationToken);
}
private async Task WriteFinalChunk(System.IO.Pipelines.PipeWriter writer, CancellationToken cancellationToken)
{
var finalChunk = CreateFinalChunk();
var finalData = $"data: {finalChunk.ToJsonString()}\n\ndata: {OpenAIStreamDoneMarker}\n\n";
await writer.WriteAsync(Encoding.UTF8.GetBytes(finalData), cancellationToken);
}
private JsonObject CreateFinalChunk()
{
return new JsonObject
{
["id"] = Guid.NewGuid().ToString(),
["object"] = "chat.completion.chunk",
["created"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
["model"] = DefaultModelName,
["choices"] = new JsonArray
{
new JsonObject
{
["index"] = 0,
["delta"] = new JsonObject(),
["finish_reason"] = "stop"
}
}
};
}
private HttpResponseMessage CreateStreamingResponse(
HttpResponseMessage originalResponse,
System.IO.Pipelines.Pipe pipeStream)
{
var newResponse = new HttpResponseMessage(originalResponse.StatusCode)
{
Content = new StreamContent(pipeStream.Reader.AsStream())
};
newResponse.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("text/event-stream");
return newResponse;
}
#endregion
}