DEV Community

Cover image for WebAPI .NET com Integração a LLM (ChatGPT)

WebAPI .NET com Integração a LLM (ChatGPT)

Neste artigo, você vai aprender como:

  • Criar uma WebAPI com .NET 8
  • Integrar com um modelo LLM via API REST (ex: ChatGPT / OpenAI)
  • Fazer requisições do cliente para geração de resposta baseada em texto
  • Ter uma base pronta para expandir para agentes inteligentes, bots e automações

🧰 Tecnologias Utilizadas

Tecnologia Descrição
.NET 8 Framework backend moderno da Microsoft
ASP.NET Web API API RESTful com C#
HttpClient Cliente HTTP para integrar com a API do LLM
OpenAI API Serviço de LLM (GPT-3.5, GPT-4, etc.)

🎯 Objetivo

Criar um endpoint que recebe uma pergunta via HTTP POST e retorna a resposta da LLM (por exemplo, GPT-4 via OpenAI API).


⚙️ Criando o Projeto .NET

dotnet new webapi -n LlmApiExample
cd LlmApiExample
Enter fullscreen mode Exit fullscreen mode

📦 Instalando Dependências

dotnet add package Microsoft.Extensions.Http
Enter fullscreen mode Exit fullscreen mode

Você também pode usar o pacote OpenAI oficial:

dotnet add package OpenAI
Enter fullscreen mode Exit fullscreen mode

📁 Estrutura do Projeto

LlmApiExample/
├── Controllers/
│   └── ChatController.cs
├── Services/
│   └── OpenAiService.cs
├── Models/
│   ├── ChatRequest.cs
│   └── ChatResponse.cs
├── Program.cs
└── appsettings.json
Enter fullscreen mode Exit fullscreen mode

📄 Models

ChatRequest.cs

namespace LlmApiExample.Models;

public class ChatRequest
{
    public string Question { get; set; } = string.Empty;
}
Enter fullscreen mode Exit fullscreen mode

ChatResponse.cs

namespace LlmApiExample.Models;

public class ChatResponse
{
    public string Answer { get; set; } = string.Empty;
}
Enter fullscreen mode Exit fullscreen mode

💬 OpenAI Service

OpenAiService.cs

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using LlmApiExample.Models;

namespace LlmApiExample.Services;

public class OpenAiService
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;

    public OpenAiService(IConfiguration config)
    {
        _httpClient = new HttpClient();
        _apiKey = config["OpenAI:ApiKey"]!;
        _httpClient.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", _apiKey);
    }

    public async Task<string> AskChatGptAsync(string prompt)
    {
        var payload = new
        {
            model = "gpt-3.5-turbo",
            messages = new[] {
                new { role = "user", content = prompt }
            }
        };

        var content = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json");

        var response = await _httpClient
            .PostAsync("https://api.openai.com/v1/chat/completions", content);

        var responseString = await response.Content.ReadAsStringAsync();

        using var jsonDoc = JsonDocument.Parse(responseString);
        return jsonDoc
            .RootElement
            .GetProperty("choices")[0]
            .GetProperty("message")
            .GetProperty("content")
            .GetString()!;
    }
}
Enter fullscreen mode Exit fullscreen mode

🎛️ Controller

ChatController.cs

using Microsoft.AspNetCore.Mvc;
using LlmApiExample.Models;
using LlmApiExample.Services;

namespace LlmApiExample.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
    private readonly OpenAiService _openAiService;

    public ChatController(OpenAiService openAiService)
    {
        _openAiService = openAiService;
    }

    [HttpPost]
    public async Task<IActionResult> Ask([FromBody] ChatRequest request)
    {
        var answer = await _openAiService.AskChatGptAsync(request.Question);
        return Ok(new ChatResponse { Answer = answer });
    }
}
Enter fullscreen mode Exit fullscreen mode

🔧 Configuração do Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSingleton<OpenAiService>();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseAuthorization();
app.MapControllers();

app.Run();
Enter fullscreen mode Exit fullscreen mode

🔐 appsettings.json

{
  "OpenAI": {
    "ApiKey": "SUA_CHAVE_SECRETA"
  }
}
Enter fullscreen mode Exit fullscreen mode

▶️ Executando a API

dotnet run
Enter fullscreen mode Exit fullscreen mode

Acesse o Swagger em:

https://localhost:5001/swagger
Enter fullscreen mode Exit fullscreen mode

Teste o endpoint POST /api/chat com:

{
  "question": "Explique o que é arquitetura hexagonal."
}
Enter fullscreen mode Exit fullscreen mode

📦 Expansões Futuras

  • Suporte a múltiplos modelos (Claude, Mistral, LLaMA)
  • Integração com agentes que mantêm contexto
  • Limite de tokens / guardrails
  • Logs e telemetria com OpenTelemetry
  • Integração com frontend (Blazor/React)

✅ Conclusão

Você agora possui uma WebAPI funcional em .NET integrada com LLMs. Isso serve como base para:

  • Chatbots inteligentes
  • Agentes de automação
  • Integração com CRMs, ERPs e mais
  • Aplicações corporativas com IA generativa

Construa, teste, e comece a criar APIs inteligentes hoje.


🤝 Conecte-se Comigo

Fique à vontade para conversar sobre IA, .NET, APIs e arquitetura moderna:


²² Porventura há, entre as vaidades dos gentios, alguém que faça chover? Ou podem os céus dar chuvas? Não és tu, ó Senhor nosso Deus? Portanto em ti esperamos, pois tu fazes todas estas coisas.

Jeremias 14:22

Top comments (0)