using Microsoft.Extensions.AI;
using OpenAI;
var builder = WebApplication.CreateBuilder(args);
var apiKey = builder.Configuration["OpenAI:ApiKey"];
if (string.IsNullOrEmpty(apiKey))
{
throw new InvalidOperationException("OpenAI API key is missing. Add it to appsettings.json (OpenAI:ApiKey), set environment variable OpenAI__ApiKey, or use user-secrets.");
}
var model = builder.Configuration["OpenAI:Model"] ?? throw new InvalidOperationException("OpenAI model is missing.");
IChatClient openAiChatClient = new OpenAIClient(apiKey).GetChatClient(model).AsIChatClient();
builder.Services.AddChatClient(openAiChatClient);
var app = builder.Build();
app.MapPost("/api/explain", async (CodeRequest request, IChatClient chatClient, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Code))
{
return Results.BadRequest(new { error = "Code is required." });
}
var prompt = $"""
You are an experienced .NET developer. Explain the following C# code in simple English. Keep your explanation below 100 words. C# Code:
{request.Code}
""";
var response = await chatClient.GetResponseAsync(prompt, cancellationToken: cancellationToken);
return Results.Ok(new CodeExplanationResponse(response.Text));
});
app.Run();
public record CodeRequest(string Code);
public record CodeExplanationResponse(string Explanation);