NTestAIApi/Controllers/AIController.cs

107 lines
3.5 KiB
C#
Raw Permalink Normal View History

2026-05-11 13:06:09 +09:00
using Google.GenAI.Types;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NTestAIApi.Controllers {
[Route("api/[controller]")]
[ApiController]
public class AIController : ControllerBase {
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
public AIController(IHttpClientFactory httpClientFactory, IConfiguration configuration) {
_httpClientFactory = httpClientFactory;
_configuration = configuration;
}
[HttpGet(Name = "GetAI")]
public async Task<IActionResult> Get([FromQuery] string question, [FromQuery] string? answer, [FromQuery] int? id) {
var apiKey = _configuration["Gemini:ApiKey"];
if (string.IsNullOrWhiteSpace(apiKey)) {
return StatusCode(500, "Gemini API 키가 설정되지 않았습니다.");
}
var url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent";
var prompt = $"문제: {question}\n정답: {answer}\n이 문제와 정답이 맞는지 간단히 설명해줘.";
var requestBody = new GeminiRequest {
Contents = new List<Content>
{
new Content
{
Parts = new List<Part>
{
new Part
{
Text = prompt
}
}
}
}
};
var client = _httpClientFactory.CreateClient();
using var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
requestMessage.Headers.Add("X-goog-api-key", apiKey);
requestMessage.Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
var response = await client.SendAsync(requestMessage);
var responseText = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) {
return StatusCode((int)response.StatusCode, responseText);
}
var geminiResponse = JsonSerializer.Deserialize<GeminiResponse>(responseText);
var resultText = geminiResponse?
.Candidates?
.FirstOrDefault()?
.Content?
.Parts?
.FirstOrDefault()?
.Text;
return Ok(new {
prompt,
result = resultText ?? "",
raw = geminiResponse
});
}
}
public class GeminiRequest {
[JsonPropertyName("contents")]
public List<Content> Contents { get; set; } = new();
}
public class Content {
[JsonPropertyName("parts")]
public List<Part> Parts { get; set; } = new();
}
public class Part {
[JsonPropertyName("text")]
public string Text { get; set; } = "";
}
public class GeminiResponse {
[JsonPropertyName("candidates")]
public List<Candidate>? Candidates { get; set; }
}
public class Candidate {
[JsonPropertyName("content")]
public CandidateContent? Content { get; set; }
}
public class CandidateContent {
[JsonPropertyName("parts")]
public List<Part>? Parts { get; set; }
}
}