top of page
Writer's pictureDrew Clark

How to create a ChatGPT Microsoft Dynamics Plugin for Customer Service Cases

How to create a Microsoft Dynamics Plugin that integrates with ChatGPT and updates the description field with the ChatGPT response

  1. Open Microsoft Visual Studio and create a new project. Choose "Class Library" as the project type and give it a name.

  2. In the project, right-click on the "References" folder and select "Add Reference". In the "Reference Manager" window, choose "Microsoft.Xrm.Sdk" and "Microsoft.Crm.Sdk.Proxy" under "Assemblies" and click "OK".

  3. Add a new class to the project and give it a meaningful name, such as "ChatGPTPlugin". This class will contain the code for the plugin.

  4. At the top of the class file, add the necessary using statements:

sqlCopy code
using System;
using System.Net.Http;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
  • Implement the "IPlugin" interface by adding the following code to the class:

javaCopy code
public class ChatGPTPlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        // Retrieve the execution context and organization serviceIPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        // Get the target entity from the execution contextEntity target = (Entity)context.InputParameters["Target"];

        // Get the case record ID from the target entityGuid caseId = target.GetAttributeValue<Guid>("incidentid");

        // Retrieve the case record using the IDColumnSet columnSet = new ColumnSet("title");
        Entity caseRecord = service.Retrieve("incident", caseId, columnSet);

        // Get the text to send to ChatGPT from the case recordstring prompt = caseRecord.GetAttributeValue<string>("title");

        // Call the ChatGPT API to generate a responsestring response = GetChatGPTResponse(prompt);

        // Update the case record with the ChatGPT response
        caseRecord["description"] = response;
        service.Update(caseRecord);
    }

    private string GetChatGPTResponse(string prompt)
    {
        using (HttpClient client = new HttpClient())
        {
            // Set the API endpoint and parametersstring endpoint = "https://api.openai.com/v1/engines/davinci-codex/completions";
            string apiKey = "YOUR_API_KEY";
            string promptText = $"Chat with me: {prompt}";

            // Create the request payloadvar payload = new
            {
                prompt = promptText,
                max_tokens = 50,
                n = 1,
                temperature = 0.5,
            };
            var jsonPayload = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");

            // Set the API request headers
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // Call the API and get the responsevar response = client.PostAsync(endpoint, jsonPayload).Result;
            var responseContent = response.Content.ReadAsStringAsync().Result;

            // Parse the response and extract the generated textdynamic responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent);
            string generatedText = responseObject.choices[0].text;

            // Return the generated textreturn generatedText;
        }
    }
}
  • Replace "YOUR_API_KEY" with

0 comments

Comments


bottom of page