Integration with OpenAI
Description
The WebForms AIPrompt allows you to easily integrate it with a Chat API service such as ChatGPT. This is thanks to the OnPromptRequest event that returns the input text (prompt), and sets the output.
If you have an OpenAI subscription, you can directly use it with the AIPrompt component.
IMPORTANT: Never share your API key with anyone or push it to GitHub/GitLab! The key will automatically be disabled by OpenAI and you will need to create a new one.
Since we got the API key, now we need to install the OpenAI Nuget package, in order to use their services. Go to the Nuget Package Manager, search for OpenAI and install the package. For more information on the library itself, you can check The official .NET library for the OpenAI API.
Solution
Now let's start the actual integration. For it, we will use the Dependency injection tehnique, to make code scalable for the future.
- Use the AIPrompt's
OnPromptRequest
event and chose/write a prompt.
<telerik:RadAIPrompt runat="server" ID="AIPrompt1" Width="400px">
<Views>
<telerik:AIPromptView Name="PromptView" Type="Prompt" />
<telerik:AIPromptView Name="OutputView" Type="Output" />
</Views>
<ClientEvents OnPromptRequest="onPromptRequest" />
</telerik:RadAIPrompt>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> promptSuggestions = new List<string>
{
"Write an out of office message",
"Write a short LinkedIn post for work/life balance.",
"Write a short email to a colleague about a project",
};
string[] sentencesArray = promptSuggestions.ToArray();
AIPrompt1.PromptSuggestions = sentencesArray;
}
}
- After finishing the prompt, click the Generate button. This will trigger the event and in the event handler make an AJAX request to the server.
let $ = $telerik.$ || $;
function onPromptRequest(sender, args) {
let prompt = args.get_prompt();
if (!prompt) {
return;
}
$.ajax({
url: 'Default.aspx/AskChatGPT',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ prompt: prompt }),
success: function (response) {
let promptOutput = {
prompt: prompt,
output: response.d
}
sender.set_activeView(1);
sender.set_promptOutput(promptOutput);
},
error: function (error) {
console.error('Error in AJAX call:', error);
}
});
}
- On the server, give some additional information how you want the response to be formatted, create a new instance of the GPTService class and use its
Ask
method.
using OpenAI.Chat;
[WebMethod]
public static string AskChatGPT(string prompt)
{
string apiKey = "API-KEY";
string model = "gpt-4o";
string textTweaks = "Respond in short, plain text (maximum of 3-4 sentences), without any formatting, such as bold text, dashes, slashes, numbering, ordered/unordered list, or special characters.";
string promptWithTweaks = string.Join("", prompt, textTweaks);
ChatClient chatClient = new ChatClient(model, apiKey);
ClientResult<ChatCompletion> completion = chatClient.CompleteChat(promptWithTweaks);
string response = completion.Value.Content[0].Text;
return response;
}
Now the integration is complete. Below you can see the result.