Skip to content

Commit 1881772

Browse files
committed
refact: use Azure.AI.OpenAI sdk from foundry
1 parent f0664d0 commit 1881772

File tree

3 files changed

+45
-49
lines changed

3 files changed

+45
-49
lines changed
Lines changed: 26 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
using System.Net.Http.Headers;
2-
using System.Text.Json;
3-
using Microsoft.AspNetCore.Mvc;
1+
using Microsoft.AspNetCore.Mvc;
42
using Microsoft.Extensions.Options;
3+
using OpenAI.Chat;
54
using chatui.Configuration;
65
using chatui.Models;
76

@@ -11,11 +10,11 @@ namespace chatui.Controllers;
1110
[Route("[controller]/[action]")]
1211

1312
public class ChatController(
14-
IHttpClientFactory httpClientFactory,
15-
IOptionsMonitor<ChatApiOptions> options,
13+
ChatClient client,
14+
IOptionsMonitor<ChatApiOptions> options,
1615
ILogger<ChatController> logger) : ControllerBase
1716
{
18-
private readonly HttpClient _client = httpClientFactory.CreateClient("ChatClient");
17+
private readonly ChatClient _client = client;
1918
private readonly IOptionsMonitor<ChatApiOptions> _options = options;
2019
private readonly ILogger<ChatController> _logger = logger;
2120

@@ -29,40 +28,32 @@ public async Task<IActionResult> Completions([FromBody] string prompt)
2928

3029
var _config = _options.CurrentValue;
3130

32-
var requestBody = JsonSerializer.Serialize(new Dictionary<string, string>
31+
HttpChatResponse response;
32+
try
3333
{
34-
[_config.ChatInputName] = prompt
35-
});
34+
ChatCompletion completion = await _client.CompleteChatAsync(
35+
[
36+
// System messages represent instructions or other guidance about how the assistant should behave
37+
new SystemChatMessage("You are a helpful Azure Chatbot assistant that answer questions about the Azure.") { ParticipantName = _config.ChatOutputName },
38+
// User messages represent user input, whether historical or the most recent input
39+
new UserChatMessage(prompt) { ParticipantName = _config.ChatInputName },
40+
]);
3641

37-
using var request = new HttpRequestMessage(HttpMethod.Post, _config.ChatApiEndpoint)
38-
{
39-
Content = new StringContent(requestBody, System.Text.Encoding.UTF8, "application/json"),
40-
};
41-
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _config.ChatApiKey);
42-
43-
var response = await _client.SendAsync(request);
44-
var responseContent = await response.Content.ReadAsStringAsync();
42+
response = new (true, completion.Content.FirstOrDefault()?.Text ?? string.Empty);
4543

46-
_logger.LogInformation("HTTP status code: {StatusCode}", response.StatusCode);
47-
48-
if (!response.IsSuccessStatusCode)
44+
_logger.LogInformation("Successfully completed chat response with: {Data}.", response.Data);
45+
}
46+
catch (Exception ex)
4947
{
50-
_logger.LogError("Error response: {Content}", responseContent);
48+
_logger.LogError("Unexpected error occurred while completing the chat: {Error}", ex.Message);
5149

52-
foreach (var (key, value) in response.Headers)
53-
_logger.LogDebug("Header {Key}: {Value}", key, string.Join(", ", value));
54-
55-
foreach (var (key, value) in response.Content.Headers)
56-
_logger.LogDebug("Content-Header {Key}: {Value}", key, string.Join(", ", value));
57-
58-
return BadRequest(responseContent);
50+
return StatusCode(503, new
51+
{
52+
success = false,
53+
error = "Service is temporarily unavailable."
54+
});
5955
}
6056

61-
_logger.LogInformation("Successful response: {Content}", responseContent);
62-
63-
var result = JsonSerializer.Deserialize<Dictionary<string, string>>(responseContent);
64-
var output = result?.GetValueOrDefault(_config.ChatOutputName) ?? string.Empty;
65-
66-
return Ok(new HttpChatResponse(true, output));
57+
return Ok(response);
6758
}
68-
}
59+
}

website/chatui/Program.cs

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
using Microsoft.Extensions.Options;
2+
using Azure;
3+
using Azure.AI.OpenAI;
14
using chatui.Configuration;
25

36
var builder = WebApplication.CreateBuilder(args);
@@ -7,19 +10,17 @@
710
.ValidateDataAnnotations()
811
.ValidateOnStart();
912

10-
builder.Services.AddHttpClient("ChatClient")
11-
.ConfigurePrimaryHttpMessageHandler(() =>
12-
{
13-
HttpClientHandler handler = new();
14-
15-
if (builder.Environment.IsDevelopment())
16-
{
17-
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
18-
handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
19-
}
20-
21-
return handler;
22-
});
13+
builder.Services.AddSingleton((provider) =>
14+
{
15+
var config = provider.GetRequiredService<IOptions<ChatApiOptions>>().Value;
16+
var openAIClient = new AzureOpenAIClient(
17+
new Uri(config.ChatApiEndpoint),
18+
new AzureKeyCredential(config.ChatApiKey));
19+
20+
// ensure this matches the custom deployment name you specified for
21+
// your model under ../../infra-as-code/bicep/openai.bicep
22+
return openAIClient.GetChatClient("gpt-35-turbo");
23+
});
2324

2425
builder.Services.AddControllersWithViews();
2526

@@ -46,4 +47,4 @@
4647

4748
app.UseCors("AllowAllOrigins");
4849

49-
app.Run();
50+
app.Run();

website/chatui/chatui.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,8 @@
77
<ItemGroup>
88
<Folder Include="wwwroot\" />
99
</ItemGroup>
10+
<ItemGroup>
11+
<PackageReference Include="Azure.AI.OpenAI" Version="2.1.0" />
12+
<PackageReference Include="Azure.Identity" Version="1.13.2" />
13+
</ItemGroup>
1014
</Project>

0 commit comments

Comments
 (0)