Skip to content

Commit 6fc95fe

Browse files
committed
refact: use Azure.AI.OpenAI sdk from foundry
1 parent 871922c commit 6fc95fe

File tree

3 files changed

+37
-37
lines changed

3 files changed

+37
-37
lines changed
Lines changed: 23 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Text.Json;
22
using Microsoft.AspNetCore.Mvc;
33
using Microsoft.Extensions.Options;
4+
using OpenAI.Chat;
45
using chatui.Configuration;
56
using chatui.Models;
67

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

1213
public class ChatGPTController(
13-
IHttpClientFactory httpClientFactory,
14+
ChatClient client,
1415
IOptions<ChatApiOptions> options,
1516
ILogger<ChatGPTController> logger) : ControllerBase
1617
{
17-
private readonly HttpClient _client = httpClientFactory.CreateClient("ChatGPT");
18+
private readonly ChatClient _client = client;
1819
private readonly ChatApiOptions _config = options.Value;
1920
private readonly ILogger<ChatGPTController> _logger = logger;
2021

@@ -26,36 +27,32 @@ public async Task<IActionResult> Completions([FromBody] string prompt)
2627

2728
_logger.LogDebug("Prompt received {Prompt}", prompt);
2829

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

34-
using var content = new StringContent(requestBody, System.Text.Encoding.UTF8, "application/json");
41+
response = new (true, completion.Content.FirstOrDefault()?.Text ?? string.Empty);
3542

36-
var response = await _client.PostAsync(string.Empty, content);
37-
var responseContent = await response.Content.ReadAsStringAsync();
38-
39-
_logger.LogInformation("HTTP status code: {StatusCode}", response.StatusCode);
40-
41-
if (!response.IsSuccessStatusCode)
43+
_logger.LogDebug("Successfully completed chat response with: {Data}.", response.Data);
44+
}
45+
catch (Exception ex)
4246
{
43-
_logger.LogError("Error response: {Content}", responseContent);
44-
45-
foreach (var (key, value) in response.Headers)
46-
_logger.LogDebug("Header {Key}: {Value}", key, string.Join(", ", value));
47+
_logger.LogError("Unexpected error occurred while completing the chat: {Error}", ex.Message);
4748

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

54-
_logger.LogDebug("Successful response: {Content}", responseContent);
55-
56-
var result = JsonSerializer.Deserialize<Dictionary<string, string>>(responseContent);
57-
var output = result?.GetValueOrDefault(_config.ChatOutputName) ?? string.Empty;
58-
59-
return Ok(new HttpChatGPTResponse(true, output));
56+
return Ok(response);
6057
}
6158
}

website/chatui/Program.cs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
using Microsoft.Extensions.Options;
2+
using Azure;
3+
using Azure.AI.OpenAI;
24
using chatui.Configuration;
35

46
var builder = WebApplication.CreateBuilder(args);
@@ -8,19 +10,16 @@
810
.ValidateDataAnnotations()
911
.ValidateOnStart();
1012

11-
builder.Services.AddHttpClient("ChatGPT", (provider, client) =>
13+
builder.Services.AddSingleton((provider) =>
1214
{
1315
var config = provider.GetRequiredService<IOptions<ChatApiOptions>>().Value;
14-
client.BaseAddress = new Uri(config.ChatApiEndpoint);
15-
client.DefaultRequestHeaders.Authorization =
16-
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", config.ChatApiKey);
17-
}).ConfigurePrimaryHttpMessageHandler(() =>
18-
{
19-
return new HttpClientHandler
20-
{
21-
ClientCertificateOptions = ClientCertificateOption.Manual,
22-
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
23-
};
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");
2423
});
2524

2625
builder.Services.AddControllersWithViews();

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)