Chat GPT Code in C#

Here's an example of how you can integrate Chat GPT API in C#:

CSharp code
using System;
 using System.Net.Http;
 using System.Threading.Tasks;
 using Newtonsoft.Json; 

class Program { 

static async Task Main(string[] args) {

var prompt = "Hello, how are you?";
var engine = "davinci";
 var maxTokens = 50; 
var apiKey = "YOUR_API_KEY";
 using (var client = new HttpClient()) { 
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey); 

var requestBody = new { prompt = prompt, max_tokens = maxTokens, engine = engine }; 
var requestJson = JsonConvert.SerializeObject(requestBody); 
var requestContent = new StringContent(requestJson, System.Text.Encoding.UTF8, "application/json"); 
var response = await client.PostAsync("", requestContent); 
var responseContent = await response.Content.ReadAsStringAsync(); dynamic responseData = JsonConvert.DeserializeObject(responseContent); 
var outputText = responseData.choices[0].text; Console.WriteLine(outputText);

This code sends a HTTP POST request to the Chat GPT API endpoint for text completion using the HttpClient class provided by .NET. The response is then parsed using the JsonConvert class from the Newtonsoft.Json library. Finally, the completed text is printed to the console.

Make sure to replace "YOUR_API_KEY" with your actual API key before running the code. Also, note that you may need to install the Newtonsoft.Json library using NuGet before using it in your project.



© 2024 - ErnesTech - Privacy
E-Commerce Return Policy