Testing ChatGPT API


Recently, I had the opportunity to test the ChatGPT REST API using .NET, and I was pleasantly surprised at how easy it was to implement.


Firstly, I used Visual Studio, which is a popular IDE for .NET development. I created a new project and added the necessary NuGet packages for HTTP client and JSON serialization. These packages made it easy to make HTTP requests to the API and parse the JSON responses.

Next, I created a test class and added test methods to it. In each test method, I made an HTTP request to a specific endpoint of the API and verified that the response was as expected. For example, in one test method, I made a GET request to the /users endpoint and verified that the response contained a list of users. In another test method, I made a POST request to the /users endpoint with a valid user object and verified that the response contained the new user's ID.

Here is an example of the code I used to make a GET request and verify the response:

 public static async Task<string> CallChatGPT(string prompt,double temperature, int maxTokens)
        {
            // Set the parameters for the API request                       
            var topP = 1.0;
            var frequencyPenalty = 0.0;
            var presencePenalty = 0.0;
            var token = "sk-xxxxxxx";
            // Create an instance of the HttpClient object
            using var httpClient = new HttpClient();
            // Set the parameters of the API request
            var requestUri = $"https://api.openai.com/v1/engines/text-davinci-003/completions";
            var requestBody = new
            {
                prompt = prompt,
                temperature = temperature,
                max_tokens = maxTokens,
                top_p = topP,
                frequency_penalty = frequencyPenalty,
                presence_penalty = presencePenalty
            };
            var requestBodyJson = JsonConvert.SerializeObject(requestBody);
            // Add the authorization token as a header to the API request
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
            // Send the API request
            using var response = await httpClient.PostAsync(requestUri, new StringContent(requestBodyJson, Encoding.UTF8, "application/json"));
            // Read and print the API response
            var responseContent = await response.Content.ReadAsStringAsync();
            return responseContent;
        }

You have to setup your API keys. Get Them from https://platform.openai.com/account/api-keys

The you can call the Method passing a question, temperature of the answer (0-cold, 1-creative) and number of tokens (words and puntaction).



Commenti

Post popolari in questo blog

FatWorms: The New Era of Burgers

Essential Developer Tools for Creating Games: My Top Picks

Cooking Through the Chaos: Hugo's Rise to Culinary Stardom