Products Technologies Demo Docs Blog Support Company

Integrating OpenAI ChatGPT with TX Text Control to Rephrase Content

ChatGPT and generative AI in general can be used to set the tone of a sentence or to rephrase content by expanding or shortening it. This example shows how to integrate OpenAI's ChatGPT into TX Text Control's document editor.

Integrating OpenAI ChatGPT with TX Text Control to Rephrase Content

ChatGPT, and generative AI in general, can be used to set the tone of a sentence or rephrase content by expanding or shortening it, and offers many interesting applications in the field of document processing. The following sample project shows how to integrate ChatGPT functionality into a document editor to rephrase the sentence at the current input position.

ChatGPT and Text Control

Requirements: OpenAI Account

To use this example, you need to create an OpenAI account with a generated API Key.

https://platform.openai.com/signup

Under User -> API Keys, create a new API Key by clicking Create new secret key.

ChatGPT and Text Control

Ribbon UI

In the example, the additional ribbon group is created as an HTML document located in the wwwroot folder that is dynamically loaded into the DOM:

TXTextControl.addEventListener("ribbonTabsLoaded", function (e) {
   $.get("/RibbonExtensions/ChatGpt/chatgpt_group.html", function (data) {
       $("#ribbonGroupClipboard").after(data);
   });
);

The chatgpt_group.html contains the HTML, CSS and JavaScript to send a HttpPost request to the RequestAPI controller method of the ChatGPTController controller.

Calling the Controller

The function basically gets the text of the paragraph at the current input position and sends a ChatGPTRequest object to the RequestAPI method. The return value is used to replace the paragraph text after a successful request.

var serviceURL = "ChatGPT/RequestAPI";
        
TXTextControl.inputPosition.getTextPosition(function(pos) {
    TXTextControl.paragraphs.getItemAtTextPosition(pos, function(par) {
        par.getText(function(content) { 

            $.ajax({
                type: "POST",
                url: serviceURL,
                contentType: "application/json",
                data: JSON.stringify({
                    text: content,
                    type: requestedType
                }),
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data) {
                $("#chatgpt-spinner").css({display: "none"});

                par.select(function() {
                    TXTextControl.selection.setText(data);
                })
            }

            function errorFunc(data) {
                console.log(data);
                $("#chatgpt-spinner").css({display: "none"});
            }

        })
    })
});

Calling OpenAI

On the server side, the controller method creates a prompt from predefined prompts for the specific call by combining it with the given text. This prompt is then sent to the OpenAI Completions API.

[HttpPost]
public string RequestAPI([FromBody] ChatGPTRequest request) {

   HttpClient client = new HttpClient();

   client.DefaultRequestHeaders.Authorization =
      new AuthenticationHeaderValue("Bearer", Models.Constants.OPENAI_API_KEY);

   var openAIPrompt = new {
      model = "text-davinci-003",
      prompt = Models.Constants.Prompts[request.Type] + request.Text.Trim(),
      temperature = 0.2,
      max_tokens = 2048,
      top_p = 1
   };

   var stringContent = new StringContent(JsonConvert.SerializeObject(openAIPrompt), Encoding.UTF8, "application/json");
   var result = client.PostAsync("https://api.openai.com/v1/completions", stringContent).Result;
   var jsonContent = result.Content.ReadAsStringAsync().Result;
   ChatGPTResponse chatGPTResponse = JsonConvert.DeserializeObject<ChatGPTResponse>(jsonContent);

   return chatGPTResponse.Choices[0].Text.Trim();
}

We have created the following sample prompts as part of the included constants:

public class Constants {
  public static string OPENAI_MODEL = "text-davinci-003";
  public static string OPENAI_API_KEY = "";

  public static readonly Dictionary<string, string> Prompts = new Dictionary<string, string>() {
        { "formal", "Return the text after the colon in a more professional way and provide the results as plain text: " },
        { "informal", "Return the text after the colon in an informal way and provide the results as plain text: " },
        { "optimistic", "Return the text after the colon in an optimistic way and provide the results as plain text: " },
        { "encouraging", "Return the text after the colon that encourages the reader and provide the results as plain text: " },
        { "expand", "Add more details to increase content length to the text after the colon and provide the results as plain text: " },
        { "shorten", "Shorten the text after the colon and provide the results as plain text: " }
  };

}

You can download the sample project for your own testing from our GitHub repository.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

Requirements for this sample

  • TX Text Control .NET Server 31.0
  • Visual Studio 2022

Related Post

ASP.NETAIChatGPT

Using OpenAI to Generate Content in TX Text Control

The OpenAI API can be used to generate content with the help of prompts. This demo implements a prompt modal window to generate content. The content is added to the TX Text control as formatted text.