Enhance Texts with Artificial Intelligence using GPT-3 in .NET
Pedro Constantino
.NET Software Engineer | Full Stack Developer | C# | Angular | AWS | Blazor
In this article, we will implement a feature in a .NET Core application that utilizes the artificial intelligence of the OpenAI GPT-3 API to suggest text improvements. By the end, you will be able to integrate an AI feature that makes texts more engaging and impactful.
Prerequisites
Step 1: Setting Up the .NET Core Project
First, create a new .NET Core web application:
dotnet new webapi -n TextEnhancer
cd TextEnhancer
Step 2: Installing Necessary NuGet Packages
We will need HttpClient for making API calls and Newtonsoft.Json for handling JSON responses. Install these packages:
dotnet add package Microsoft.Extensions.Http
dotnet add package Newtonsoft.Json
Step 3: Creating the API Service
Create a service to interact with the GPT-3 API. Add a new folder Services and create a Gpt3Service.cs class inside it:
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace TextEnhancer.Services
{
public class Gpt3Service
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
public Gpt3Service(HttpClient httpClient, string apiKey)
{
_httpClient = httpClient;
_apiKey = apiKey;
}
public async Task<string> EnhanceTextAsync(string text)
{
var requestBody = new
{
prompt = $"Improve the following text: {text}",
max_tokens = 60
};
var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
var response = await _httpClient.PostAsync("https://api.openai.com/v1/engines/davinci- codex/completions", content);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
dynamic result = JsonConvert.DeserializeObject(responseContent);
return result.choices[0].text.Trim();
}
}
}
Step 4: Configuring the API Key
Add your OpenAI API key to appsettings.json:
{
"OpenAI": {
"ApiKey": "YOUR_API_KEY"
}
}
Then, load this configuration in Startup.cs:
领英推荐
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<Gpt3Service>((sp, client) =>
{
var apiKey = Configuration["OpenAI:ApiKey"];
return new Gpt3Service(client, apiKey);
});
services.AddControllers();
}
Step 5: Creating the Controller
Create a new controller TextController.cs to handle the request and use the Gpt3Service:
using Microsoft.AspNetCore.Mvc;
using TextEnhancer.Services;
using System.Threading.Tasks;
namespace TextEnhancer.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class TextController : ControllerBase
{
private readonly Gpt3Service _gpt3Service;
public TextController(Gpt3Service gpt3Service)
{
_gpt3Service = gpt3Service;
}
[HttpPost("enhance-text")]
public async Task<IActionResult> EnhanceText([FromBody] string text)
{
var enhancedText = await _gpt3Service.EnhanceTextAsync(text);
return Ok(new { originalText = text, enhancedText });
}
}
}
Step 6: Testing the API
Run your application:
dotnet run
Send a POST request to https://localhost:5000/api/text/enhance-text with a JSON body containing the text you want to enhance:
{
"text": "Today was a good day."
}
You should receive a response with the original text and the enhanced text:
{
"originalText": "Today was a good day.",
"enhancedText": "Today was an exceptional day, filled with achievements and pleasant moments."
}
Conclusion
By following these steps, you have integrated the artificial intelligence of the OpenAI GPT-3 API into a .NET Core application to enhance texts. This example can be further expanded to include more advanced features and configurations, making your application more dynamic and engaging.
#ArtificialIntelligence #GPT3 #OpenAI #SoftwareDevelopment #DotNetCore #APIs #TextEnhancement
Senior Software Engineer | Solution Architect | Developer | Java | Angular | Spring Boot | Microservices | Full-stack
8 个月I'll keep this in mind
Full Stack Engineer | React | Node | JavaScript | Typescript | Next | MERN Developer
8 个月Awesome guide! Integrating GPT-3 with .NET Core to enhance text sounds like a game-changer for creating engaging content. ??
.NET Developer | C# | TDD | Angular | Azure | SQL
8 个月Insightful!
Data Engineer | Azure/AWS | Python & SQL Specialist | ETL & Data Pipeline Expert
8 个月Great read!