Skip to content

Commit e0481c7

Browse files
Merge pull request #6765 from syncfusion-content/983717-Azure-openai-integration-chatui
983717: Change the integration using the Azure openai
2 parents 8744c3a + f4e2212 commit e0481c7

File tree

3 files changed

+129
-72
lines changed

3 files changed

+129
-72
lines changed

blazor/ai-assistview/ai-integrations/openai-integration.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Nuget\Install-Package Syncfusion.Blazor.InteractiveChat
3232

3333
```
3434

35-
Install the Markdown rendering package used to convert model responses to HTML.
35+
Install the `Open AI` and `Markdig` nuget packages in the application.
3636

3737
```bash
3838

@@ -59,7 +59,7 @@ Note: The sample below uses HttpClient directly and does not require the Azure/O
5959
6060
## Integration Azure OpenAI with AI AssistView
6161

62-
- Configure your Azure OpenAI endpoint, API key, and deployment name in your Program.cs (or using your preferred configuration mechanism).
62+
- Configure your Azure OpenAI endpoint, API key, and deployment name in your **Program.cs** (or using your preferred configuration mechanism).
6363

6464
- Register the service for dependency injection.
6565

blazor/chat-ui/ai-integrations/gemini-integration.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,4 +132,4 @@ const string GeminiApiKey = 'Place your API key here';
132132
{% endhighlight %}
133133
{% endtabs %}
134134

135-
![Blazor Chat UI Gemini Integration](./images/gemini-integration.png)
135+
![Blazor Chat UI Gemini Integration](../images/gemini-integration.png)
Lines changed: 126 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,80 @@
11
---
22
layout: post
3-
title: Open AI Integration with Blazor Chat UI Component | Syncfusion
4-
description: Checkout and learn about Open AI integration with Blazor Chat UI component in Blazor WebAssembly Application.
3+
title: Azure Open AI with Blazor Chat UI Component | Syncfusion
4+
description: Checkout and learn about Azure Open AI with Blazor Chat UI component in Blazor WebAssembly Application.
55
platform: Blazor
66
control: Chat UI
77
documentation: ug
88
---
99

10-
# Integration of Open AI With Blazor Chat UI component
10+
# Integration of Azure OpenAI With Blazor Chat UI component
1111

12-
The Syncfusion Chat UI supports integration with [OpenAI](https://platform.openai.com/docs/overview), enabling advanced conversational AI features in your applications.
12+
The Syncfusion Chat UI supports integration with [Azure Open AI](https://microsoft.github.io/PartnerResources/skilling/ai-ml-academy/resources/openai), enabling advanced conversational AI features in your applications.
1313

1414
## Prerequisites
1515

16-
* OpenAI account to generate an API key for accessing the `OpenAI` API
17-
* Syncfusion Chat UI for Blazor `Syncfusion.Blazor.InteractiveChat` installed in your project.
16+
- An Azure account with access to `Azure Open AI` services and a generated API key.
17+
- Syncfusion Chat UI for Blazor `Syncfusion.Blazor.InteractiveChat` installed in the project
1818

1919
## Getting Started with the Chat UI Component
2020

21-
Before integrating Open AI, ensure that the Syncfusion Chat UI is correctly rendered in your application:
21+
Before integrating Azure OpenAI, ensure the Syncfusion Chat UI component renders correctly in the application:
2222

23-
[ Blazor Getting Started Guide](../getting-started)
23+
[Blazor Getting Started Guide](../getting-started)
2424

2525
## Install Dependencies
2626

2727
Install the Syncfusion Blazor package in the application.
2828

2929
```bash
3030

31-
Install-Package Syncfusion.Blazor.InteractiveChat
31+
Nuget\Install-Package Syncfusion.Blazor.InteractiveChat
3232

3333
```
3434

35-
Install the Open AI AI package in the application.
35+
Install the `Open AI` and `Markdig` nuget packages in the application.
3636

3737
```bash
3838

39-
Install-Package OpenAI
39+
NuGet\Install-Package OpenAI
40+
NuGet\Install-Package Azure.AI.OpenAI
41+
NuGet\Install-Package Azure.Core
42+
Nuget\Install-Package Markdig
4043

4144
```
4245

43-
## Generate API Key
46+
Note: The sample below uses HttpClient directly and does not require the Azure/OpenAI SDKs.
4447

45-
1. Go to [Open AI](https://platform.openai.com/docs/overview) and sign in with your Google account. If you don’t have one, create a new account.
48+
## Configure Azure Open AI
4649

47-
2. Once logged in, click on your profile icon in the top-right corner and select `API Keys` from the dropdown menu.
50+
1. Log in to the [Azure Portal](https://portal.azure.com/#home) and navigate to your Azure Open AI resource.
4851

49-
3. Click the `+ Create new secret key` button. You’ll be prompted to name the key (optional). Confirm to generate the key.
52+
2. Under Resource Management, select Keys and Endpoint to retrieve your API key and endpoint URL.
5053

51-
4. Your API key will be displayed once. Copy it and store it securely, as it won’t be shown again.
54+
3. Copy the API key, endpoint, and deployment name (e.g., gpt-4o-mini). Ensure the API version (e.g., 2024-07-01-preview) matches your resource configuration.
5255

53-
> `Security Note`: Never commit the API key to version control. Use environment variables or a secret manager for production.
56+
4. Store these values securely, as they will be used in your application.
5457

55-
## Integration Open AI with Chat UI
58+
> `Security Note`: expose your API key in client-side code for production applications. Use a server-side proxy or environment variables to manage sensitive information securely.
5659
57-
* Add your generated `API Key` at the line
60+
## Integration Azure OpenAI with Chat UI
5861

59-
```bash
62+
- Configure your Azure OpenAI endpoint, API key, and deployment name in your **Program.cs** (or using your preferred configuration mechanism).
6063

61-
const string openaiApiKey = 'Place your API key here';
64+
- Register the service for dependency injection.
6265

63-
```
66+
- Inject and use the service in your Razor component.
6467

6568
{% tabs %}
66-
{% highlight razor %}
69+
{% highlight c# tabtitle="razor" %}
70+
71+
@using Blazor_ChatUI_AI.Components.Services
72+
@using Syncfusion.Blazor.InteractiveChat
73+
@using Syncfusion.Blazor.Navigations
74+
@inject AzureOpenAIService OpenAIService
6775

68-
<div class="aiassist-container" style="height: 350px; width: 650px;">
69-
<SfChatUI ID="chatUI" User="currentUser" HeaderText="Chat with OpenAI" HeaderIconCss="e-icons e-ai-chat" Messages="@Messages" MessageSend="OnMessageSend" TypingUsers="@typingUsers">
76+
<div class="chatui-container" style="height: 450px; width:450px;">
77+
<SfChatUI ID="chatUser" HeaderText="Chat with OpenAI" HeaderIconCss="e-icons e-ai-chat" User="CurrentUserModel" Messages="ChatUserMessages" MessageSend="@MessageSend" TypingUsers="@typingUsers">
7078
<ChildContent>
7179
<HeaderToolbar ItemClicked="@ToolbarItemClicked">
7280
<HeaderToolbarItem Type="ItemType.Spacer"></HeaderToolbarItem>
@@ -83,62 +91,111 @@ const string openaiApiKey = 'Place your API key here';
8391
</div>
8492

8593
@code {
86-
private UserModel currentUser = new() { ID = "user1", User = "You" };
87-
private UserModel aiUser = new() { ID = "ai", User = "Open AI" };
88-
private List<ChatMessage> Messages { get; set; } = new();
94+
private static UserModel CurrentUserModel = new UserModel() { ID = "User1", User = "You" };
95+
private static UserModel OpenAIModel = new UserModel() { ID = "User2", User = "OpenAI" };
96+
97+
private List<ChatMessage> ChatUserMessages = new List<ChatMessage>();
8998
private List<UserModel> typingUsers = new();
90-
private string openaiApiKey = "";
9199

92-
private async Task OnMessageSend(ChatMessageSendEventArgs args)
100+
private async Task MessageSend(ChatMessageSendEventArgs args)
93101
{
94-
// Indicate AI is typing
95-
typingUsers = new List<UserModel> { aiUser };
96-
await Task.Delay(500); // Simulate typing delay
97-
98-
try
102+
typingUsers = new List<UserModel> { OpenAIModel };
103+
string response = await OpenAIService.GetChatResponseAsync(args.Message.Text);
104+
ChatUserMessages.Add(new ChatMessage()
99105
{
100-
var openAiClient = new OpenAIClient(openaiApiKey);
101-
var chatClient = openAiClient.GetChatClient("gpt-4o-mini");
102-
103-
OpenAI.Chat.ChatCompletion completion = await chatClient.CompleteChatAsync(args.Message.Text);
104-
string responseText = completion.Content[0].Text;
105-
var pipeline = new MarkdownPipelineBuilder()
106-
.UseAdvancedExtensions()
107-
.UsePipeTables()
108-
.UseTaskLists()
109-
.Build();
110-
// Add AI response to messages
111-
Messages.Add(new ChatMessage
112-
{
113-
Text = Markdown.ToHtml(responseText, pipeline),
114-
Author = aiUser
115-
});
116-
}
117-
catch (Exception ex)
118-
{
119-
Console.WriteLine($"Error fetching OpenAI response: {ex.Message}");
120-
Messages.Add(new ChatMessage
121-
{
122-
Text = "Error generating response. Please try again.",
123-
Author = aiUser
124-
});
125-
StateHasChanged();
126-
}
127-
finally
128-
{
129-
typingUsers.Clear();
130-
StateHasChanged();
131-
}
106+
ID = Guid.NewGuid().ToString(),
107+
Text = response,
108+
Author = OpenAIModel
109+
});
110+
typingUsers.Clear();
132111
}
133112

134113
private async Task ToolbarItemClicked()
135114
{
136-
Messages.Clear();
115+
ChatUserMessages.Clear();
137116
StateHasChanged();
138117
}
139118
}
140119

120+
{% endhighlight %}
121+
{% highlight c# tabtitle="cs" %}
122+
123+
using System.Net.Http.Json;
124+
using System.Text.Json;
125+
using Markdig;
126+
using System.Text.RegularExpressions;
127+
128+
namespace Blazor_ChatUI_AI.Components.Services
129+
{
130+
public class AzureOpenAIService
131+
{
132+
private readonly HttpClient _httpClient;
133+
private readonly string _endpoint;
134+
private readonly string _apiKey;
135+
private readonly string _deploymentName;
136+
137+
public AzureOpenAIService(HttpClient httpClient, string endpoint, string apiKey, string deploymentName)
138+
{
139+
_httpClient = httpClient;
140+
_endpoint = endpoint;
141+
_apiKey = apiKey;
142+
_deploymentName = deploymentName;
143+
}
144+
145+
public async Task<string> GetChatResponseAsync(string prompt)
146+
{
147+
var request = new
148+
{
149+
messages = new[] { new { role = "user", content = prompt } },
150+
max_tokens = 500,
151+
};
152+
153+
var url = $"{_endpoint}/openai/deployments/{_deploymentName}/chat/completions?api-version=2024-02-15-preview";
154+
_httpClient.DefaultRequestHeaders.Add("api-key", _apiKey);
155+
156+
try
157+
{
158+
var response = await _httpClient.PostAsJsonAsync(url, request);
159+
160+
if (response.IsSuccessStatusCode)
161+
{
162+
var responseContent = await response.Content.ReadAsStringAsync();
163+
using var jsonDocument = JsonDocument.Parse(responseContent);
164+
var choices = jsonDocument.RootElement.GetProperty("choices");
165+
166+
if (choices.GetArrayLength() > 0)
167+
{
168+
var content = choices[0].GetProperty("message").GetProperty("content").GetString();
169+
var htmlContent = Markdown.ToHtml(content);
170+
htmlContent = Regex.Replace(htmlContent, @"\s+", " ").Trim();
171+
return htmlContent; // Return the full response
172+
}
173+
else
174+
{
175+
return "Error: No choices returned in the response.";
176+
}
177+
}
178+
else
179+
{
180+
return $"Error: {await response.Content.ReadAsStringAsync()}";
181+
}
182+
}
183+
catch (Exception ex)
184+
{
185+
return $"Error: {ex.Message}";
186+
}
187+
}
188+
}
189+
}
190+
191+
{% endhighlight %}
192+
{% highlight c# tabtitle="Server(~/_Program.cs)" %}
193+
194+
var endpoint = "https://azure-testresource.openai.azure.com";
195+
var apiKey = "<Your API Key>"; // Replace with your API key;
196+
var deploymentName = "gpt-4o-mini";
197+
141198
{% endhighlight %}
142199
{% endtabs %}
143200

144-
![Blazor Chat UI Open AI Integration](./images/openai-integration.png)
201+
![Blazor Chat UI Azure Open AI Integration](../images/openai-integration.png)

0 commit comments

Comments
 (0)