Skip to content

Changed AI Model to Microsoft Extension AI and Removed extra space for smart redaction sample #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
90 changes: 61 additions & 29 deletions AI Demos/AISmartPDFFormFill/SmartFill/AIHelper.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
using Azure.AI.OpenAI;
using Microsoft.Extensions.AI;
using Azure.AI.OpenAI;
using Azure;

namespace SmartFill
{
public class AIHelper
public class AIHelper
{

#region Fields

/// <summary>
/// The EndPoint
/// </summary>
@@ -14,35 +17,64 @@ public class AIHelper
/// <summary>
/// The Deployment name
/// </summary>
internal string deploymentName = "DEPLOYMENT_NAME";
internal string DeploymentName = "DEPLOYMENT_NAME";

/// <summary>
/// The AI key
/// </summary>
private string apiKey = "AZURE_OPENAI_API_KEY";
private string key = "OPENAI_AI_KEY";

/// <summary>
/// The IChatClient instance
/// </summary>
private IChatClient? client;

/// <summary>
/// The chat history
/// </summary>
private string? chatHistory;

#endregion

#region Properties

/// <summary>
/// The AzureOpenAI client
/// Gets or sets the chat history
/// </summary>
// C#
internal OpenAIClient? openAIClient;
public string? ChatHistory
{
get { return chatHistory; }
set { chatHistory = value; }
}

/// <summary>
/// The ChatCompletion option
/// Gets or sets the IChatClient instance
/// </summary>
private ChatCompletionsOptions? chatCompletionsOptions;
public IChatClient? Client
{
get { return client; }
set { client = value; }
}

#endregion

#region Constructor

public AIHelper()
{
chatCompletionsOptions = new ChatCompletionsOptions
{
DeploymentName = deploymentName,
Temperature = (float)1.2f,
NucleusSamplingFactor = (float)0.9,
FrequencyPenalty = 0.8f,
PresencePenalty = 0.8f
};
openAIClient = new OpenAIClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
InitializeClient();
}

#endregion

#region Methods

/// <summary>
/// Initializes the Azure OpenAI client
/// </summary>
private void InitializeClient()
{
client = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key)).AsChatClient(modelId: DeploymentName);
}

/// <summary>
@@ -54,24 +86,24 @@ public async Task<string> GetChatCompletion(string userPrompt)
{
try
{
if (apiKey != "AZURE_OPENAI_API_KEY" && deploymentName != "DEPLOYMENT_NAME" && endpoint != "https://yourendpoint.com/")
if (key != "OPENAI_AI_KEY" && DeploymentName != "DEPLOYMENT_NAME" && endpoint != "https://yourendpoint.com/" && Client!=null)
{
chatCompletionsOptions.Messages.Add(new ChatRequestUserMessage(userPrompt));
var response = await openAIClient.GetChatCompletionsAsync(chatCompletionsOptions);
return response.Value.Choices[0].Message.Content;
ChatHistory = string.Empty;
ChatHistory = ChatHistory + userPrompt;
var response = await Client.CompleteAsync(ChatHistory);
return response.ToString();
}
else
{
await Application.Current.MainPage.DisplayAlert("Error", "Please provide your Azure OpenAI API key, deployment name, and endpoint in the AIHelper class.", "OK");
return string.Empty;
return " ";
}
}
catch (Exception exception)
catch
{
await Application.Current.MainPage.DisplayAlert("Error", exception.Message, "OK");
return string.Empty;
// Return an empty string if an exception occurs
return " ";
}
}

#endregion
}
}
}
5 changes: 4 additions & 1 deletion AI Demos/AISmartPDFFormFill/SmartFill/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Syncfusion.Maui.PdfViewer;
using Syncfusion.Pdf.Parsing;
using System.Net;

namespace SmartFill;

@@ -31,12 +32,14 @@ private void PdfViewer_DocumentLoaded(object? sender, EventArgs? e)
#if ANDROID || IOS
MobileCopiedData.IsVisible = true;
#endif
if (chatService.DeploymentName != "DEPLOYMENT_NAME")
SubmitForm.IsEnabled = true;
}

private async void Clipboard_ClipboardContentChanged(object? sender, EventArgs e)
{
string? copiedText = await Clipboard.GetTextAsync();
if (string.IsNullOrEmpty(copiedText) == false && chatService.deploymentName!= "DEPLOYMENT_NAME")
if (string.IsNullOrEmpty(copiedText) == false && chatService.DeploymentName!= "DEPLOYMENT_NAME")
{
SubmitForm.IsEnabled = true;
StartBubbleAnimation();
6 changes: 5 additions & 1 deletion AI Demos/AISmartPDFFormFill/SmartFill/SmartFill.csproj
Original file line number Diff line number Diff line change
@@ -86,7 +86,11 @@
<PackageReference Include="Syncfusion.Maui.ListView" Version="*" />
<PackageReference Include="Syncfusion.Maui.PdfToImageConverter" Version="*" />
<PackageReference Include="Syncfusion.Pdf.Imaging.NET" Version="*" />
<PackageReference Include="Azure.AI.OpenAI" Version="1.0.0-beta.15" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.0.0" />
<PackageReference Include="Azure.Identity" Version="1.13.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.0.1-preview.1.24570.5" />
<PackageReference Include="System.Private.Uri" Version="4.3.2" />

</ItemGroup>

</Project>
94 changes: 69 additions & 25 deletions AI Demos/SmartRedaction/SmartRedaction/AIService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
using Azure;
using Microsoft.Extensions.AI;
using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI;
using Azure;

namespace SmartRedaction
{
public class AIService
{
#region Fields

/// <summary>
/// The EndPoint
/// </summary>
@@ -18,49 +23,88 @@ public class AIService
/// <summary>
/// The AI key
/// </summary>
private string key = "AZURE_OPENAI_API_KEY";
private string key = "OPENAI_AI_KEY";

/// <summary>
/// The IChatClient instance
/// </summary>
private IChatClient client;

/// <summary>
/// The chat history
/// </summary>
private string chatHistory;

#endregion

#region Properties

/// <summary>
/// The AzureOpenAI client
/// Gets or sets the chat history
/// </summary>
private OpenAIClient? client;
public string ChatHistory
{
get { return chatHistory; }
set { chatHistory = value; }
}

/// <summary>
/// The ChatCompletion option
/// Gets or sets the IChatClient instance
/// </summary>
internal ChatCompletionsOptions? chatCompletions;
public IChatClient Client
{
get { return client; }
set { client = value; }
}

#endregion

#region Constructor

public AIService()
{
chatCompletions = new ChatCompletionsOptions
{
DeploymentName = this.DeploymentName,
Temperature = (float)1.2f,
NucleusSamplingFactor = (float)0.9,
FrequencyPenalty = 0.8f,
PresencePenalty = 0.8f
};
client = new OpenAIClient(new Uri(this.endpoint), new AzureKeyCredential(this.key));
InitializeClient();
}
public async Task<string> GetAnswerFromGPT(string systemPrompt, string extractedtext)

#endregion

#region Methods

/// <summary>
/// Initializes the Azure OpenAI client
/// </summary>
private void InitializeClient()
{
client = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key)).AsChatClient(modelId: DeploymentName);
}

/// <summary>
/// Retrieves an answer from the GPT model using the provided system prompt and extracted text.
/// </summary>
/// <param name="systemPrompt">The system instruction for GPT.</param>
/// <param name="extractedText">The input text extracted from a source.</param>
/// <returns>A string containing the response from OpenAI or an empty string if an error occurs.</returns>
public async Task<string> GetAnswerFromGPT(string systemPrompt, string extractedText)
{
try
{
string message = extractedtext;
if (this.client != null && this.chatCompletions != null && this.key != "AZURE_OPENAI_API_KEY")
if (Client != null && key != "OPENAI_API_KEY")
{
chatCompletions.Messages.Clear();
chatCompletions.Messages.Add(new ChatRequestSystemMessage(systemPrompt));
chatCompletions.Messages.Add(new ChatRequestUserMessage(message));
var response = await client.GetChatCompletionsAsync(chatCompletions);
return response.Value.Choices[0].Message.Content;
ChatHistory = string.Empty;
ChatHistory += $"System: {systemPrompt}\nUser: {extractedText}";
var response = await Client.CompleteAsync(ChatHistory);
return response.ToString();
}
return "";
else
return string.Empty;
}
catch
{
return "";
// Return an empty string if an exception occurs
return string.Empty;
}
}

#endregion
}
}
8 changes: 4 additions & 4 deletions AI Demos/SmartRedaction/SmartRedaction/MainPage.xaml
Original file line number Diff line number Diff line change
@@ -454,7 +454,7 @@
HeightRequest="40"
HorizontalOptions="End"
Clicked="OnCancelClicked" />
<Button Text="Apply"
<Button Text="Ok"
x:Name="SelectRedactItem_Mobile"
IsEnabled="False"
Style="{StaticResource ApplyButton}"
@@ -484,8 +484,8 @@
IsVisible="{OnPlatform WinUI=True,MacCatalyst=True,Default=False}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="7*" />
<RowDefinition Height="4*" />
<RowDefinition Height="{OnPlatform WinUI='5*', MacCatalyst='3*'}" />
<RowDefinition Height="6*" />
</Grid.RowDefinitions>

<!-- Label -->
@@ -655,7 +655,7 @@
Clicked="OnCancelClicked">
</Button>
<Button x:Name="SelectRedactitem"
Text="Apply"
Text="Ok"
IsEnabled="False"
CornerRadius="20"
FontAttributes="Bold"
10 changes: 10 additions & 0 deletions AI Demos/SmartRedaction/SmartRedaction/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -69,6 +69,16 @@ private void OkClicked(object sender, EventArgs e)
{
AddRedact.IsEnabled = true;
MobileRedactLayout.IsVisible = false;
#if WINDOWS || MACCATALYST
popupContainer.IsVisible = !popupContainer.IsVisible;
SenstiveInfoContainer.IsVisible = false;
SelectRedactitem.IsEnabled = false;
#else
popupContainerMobile.IsVisible = !popupContainerMobile.IsVisible;
SenstiveInfoContainerMobile.IsVisible = false;
#endif
ViewModel.SensitiveInfo.Clear();

}

private void PdfViewer_AnnotationAdded(object? sender, AnnotationEventArgs e)
11 changes: 7 additions & 4 deletions AI Demos/SmartRedaction/SmartRedaction/SmartRedaction.csproj
Original file line number Diff line number Diff line change
@@ -69,10 +69,13 @@
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.Maui.Controls.Compatibility" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="Syncfusion.Maui.Buttons" Version="26.2.11" />
<PackageReference Include="Syncfusion.Maui.PdfViewer" Version="26.2.11" />
<PackageReference Include="Syncfusion.Maui.TreeView" Version="26.2.11" />
<PackageReference Include="Azure.AI.OpenAI" Version="1.0.0-beta.15" />
<PackageReference Include="Syncfusion.Maui.Buttons" Version="27.1.50" />
<PackageReference Include="Syncfusion.Maui.PdfViewer" Version="27.1.50" />
<PackageReference Include="Syncfusion.Maui.TreeView" Version="27.1.50" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.0.0" />
<PackageReference Include="Azure.Identity" Version="1.13.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.0.1-preview.1.24570.5" />
<PackageReference Include="System.Private.Uri" Version="4.3.2" />
</ItemGroup>

</Project>
89 changes: 56 additions & 33 deletions AI Demos/Summarizer/Summarizer/AssistServices.cs
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@
using System.Collections.ObjectModel;
using Azure.AI.OpenAI;
using Azure;
using Microsoft.Extensions.AI;

namespace Summarizer
{
@@ -11,6 +12,7 @@ namespace Summarizer
/// </summary>
internal class AssistServices
{
#region Fields

/// <summary>
/// Gets or sets the extracted text from a document.
@@ -30,29 +32,53 @@ internal class AssistServices
/// <summary>
/// The AI key
/// </summary>
private string key = "AZURE_OPENAI_API_KEY";
private string key = "OPENAI_AI_KEY";

/// <summary>
/// The AzureOpenAI client
/// The IChatClient instance
/// </summary>
internal OpenAIClient? client;
private IChatClient? client;

/// <summary>
/// The ChatCompletion option
/// The chat history
/// </summary>
private ChatCompletionsOptions? chatCompletions;
private string? chatHistory;

#endregion

#region Properties

/// <summary>
/// Gets or sets the chat history
/// </summary>
public string? ChatHistory
{
get { return chatHistory; }
set { chatHistory = value; }
}

/// <summary>
/// Gets or sets the IChatClient instance
/// </summary>
public IChatClient? Client
{
get { return client; }
set { client = value; }
}

#endregion

internal AssistServices()
{
chatCompletions = new ChatCompletionsOptions
{
DeploymentName = this.DeploymentName,
Temperature = (float)1.2f,
NucleusSamplingFactor = (float)0.9,
FrequencyPenalty = 0.8f,
PresencePenalty = 0.8f
};
client = new OpenAIClient(new Uri(this.endpoint), new AzureKeyCredential(this.key));
InitializeClient();
}

/// <summary>
/// Initializes the Azure OpenAI client
/// </summary>
private void InitializeClient()
{
client = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key)).AsChatClient(modelId: DeploymentName);
}

/// <summary>
@@ -62,13 +88,12 @@ internal AssistServices()
/// <returns>A predefined message requesting OpenAI connection for real-time queries.</returns>
internal async Task<string> GetPrompt(string prompt)
{
if (this.client != null && this.chatCompletions != null && this.key != "AZURE_OPENAI_API_KEY")
if (this.Client != null && key != "OPENAI_AI_KEY")
{
chatCompletions.Messages.Clear();
chatCompletions.Messages.Add(new ChatRequestSystemMessage("Please provide the prompt for responce" + prompt));
chatCompletions.Messages.Add(new ChatRequestUserMessage(prompt));
var response = await client.GetChatCompletionsAsync(chatCompletions);
return response.Value.Choices[0].Message.Content;
ChatHistory = string.Empty;
ChatHistory += $"System: {"Please provide the prompt for responce" + prompt}\nUser: {prompt}";
var response = await Client.CompleteAsync(ChatHistory);
return response.ToString();
}
else
return "Please connect OpenAI for real time queries";
@@ -85,15 +110,14 @@ internal async Task<string> GetSolutionToPrompt(string question)
try
{
// Use extracted text
if (this.ExtractedText != null && this.client != null && this.chatCompletions != null && this.key != "AZURE_OPENAI_API_KEY")
if (this.ExtractedText != null && this.Client != null && key != "OPENAI_AI_KEY")
{
string message = ExtractedText;
var systemPrompt = "You are a helpful assistant. Use the provided PDF document pages and pick a precise page to answer the user question,Ignore about iTextSharp related points in the details, Strictly don't bold any text all text need to plain text. Pages: " + message;
chatCompletions.Messages.Clear();
chatCompletions.Messages.Add(new ChatRequestSystemMessage(systemPrompt));
chatCompletions.Messages.Add(new ChatRequestUserMessage(question));
var response = await client.GetChatCompletionsAsync(chatCompletions);
return response.Value.Choices[0].Message.Content;
var systemPrompt = "Read the PDF document contents, understand the concept, and select the precise page to answer the user's question. Ignore any points related to iTextSharp. Ensure that all text is plain and not bolded. Pages: Question: " + question;
ChatHistory = string.Empty;
ChatHistory += $"System: {systemPrompt}\nUser: {ExtractedText}";
var response = await Client.CompleteAsync(ChatHistory);
return response.ToString();
}
return "Please connect OpenAI for real time queries";
}
@@ -137,13 +161,12 @@ internal async Task<string> GetAnswerFromGPT(string systemPrompt)
{
try
{
if (this.ExtractedText != null && this.chatCompletions != null && this.client != null && this.key != "AZURE_OPENAI_API_KEY")
if (this.ExtractedText != null && this.Client != null && key != "OPENAI_AI_KEY")
{
chatCompletions.Messages.Clear();
chatCompletions.Messages.Add(new ChatRequestSystemMessage(systemPrompt));
chatCompletions.Messages.Add(new ChatRequestUserMessage(ExtractedText));
var response = await client.GetChatCompletionsAsync(chatCompletions);
return response.Value.Choices[0].Message.Content;
ChatHistory = string.Empty;
ChatHistory += $"System: {systemPrompt}\nUser: {ExtractedText}";
var response = await Client.CompleteAsync(ChatHistory);
return response.ToString();
}
else
return "Please connect OpenAI for real time queries";
20 changes: 0 additions & 20 deletions AI Demos/Summarizer/Summarizer/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -53,26 +53,6 @@ internal async Task LoadPDFDataAsync()
PdfLoadedPageCollection loadedPages = loadedDocument.Pages;
await Task.Run(() =>
{
// Extract annotations to a memory stream and convert to string
using (MemoryStream annotationStream = new MemoryStream())
{
loadedDocument.ExportAnnotations(annotationStream, AnnotationDataFormat.Json);
string annotations = ConvertToString(annotationStream);
if (!String.IsNullOrEmpty(annotations))
extractedText.Add("Annotations: " + annotations);
}

// Extract form fields to a memory stream and convert to string
using (MemoryStream formStream = new MemoryStream())
{
if (loadedDocument.Form != null)
{
loadedDocument.Form.ExportData(formStream, DataFormat.Json, "form");
string formFields = ConvertToString(formStream);
if (!String.IsNullOrEmpty(formFields))
extractedText.Add("Form fields: " + formFields);
}
}
// Extract text from existing PDF document pages
for (int i = 0; i < loadedPages.Count; i++)
{
4 changes: 3 additions & 1 deletion AI Demos/Summarizer/Summarizer/Summarizer.csproj
Original file line number Diff line number Diff line change
@@ -80,7 +80,6 @@
<PackageReference Include="Syncfusion.Maui.Inputs" Version="*" />
<PackageReference Include="Syncfusion.Maui.Picker" Version="*" />
<PackageReference Include="Syncfusion.Maui.Popup" Version="*" />
<PackageReference Include="Azure.AI.OpenAI" Version="1.0.0-beta.15" />
<PackageReference Include="Syncfusion.Maui.Core" Version="*" />
<PackageReference Include="Syncfusion.Maui.Buttons" Version="*" />
<PackageReference Include="Syncfusion.Maui.SignaturePad" Version="*" />
@@ -91,6 +90,9 @@
<PackageReference Include="Syncfusion.Maui.Sliders" Version="*" />
<PackageReference Include="Syncfusion.Maui.TabView" Version="*" />
<PackageReference Include="Syncfusion.Pdf.Imaging.NET" Version="*" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.0.0" />
<PackageReference Include="Azure.Identity" Version="1.13.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.0.1-preview.1.24570.5" />
</ItemGroup>

</Project>
32 changes: 0 additions & 32 deletions AI Demos/Summarizer/Summarizer/Summarizer.csproj.user

This file was deleted.