first commit
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Fitness_core_BE.AI
|
||||
{
|
||||
public class GeminiClient : IAiClient
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly IConfiguration _config;
|
||||
|
||||
public GeminiClient(HttpClient http, IConfiguration configuration)
|
||||
{
|
||||
_http = http;
|
||||
_config = configuration;
|
||||
}
|
||||
|
||||
public async Task<string> GenerateJsonAsync( string systemPrompt, object payload)
|
||||
{
|
||||
string apiKey = _config["Gemini:ApiKey"];
|
||||
|
||||
if (string.IsNullOrEmpty(apiKey))
|
||||
throw new Exception("Gemini API key is not configured.");
|
||||
|
||||
var requestBody = new
|
||||
{
|
||||
contents = new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
parts = new[]
|
||||
{
|
||||
new { text = systemPrompt },
|
||||
new { text = JsonSerializer.Serialize(payload) }
|
||||
}
|
||||
}
|
||||
},
|
||||
generationConfig = new
|
||||
{
|
||||
temperature = 0.4,
|
||||
maxOutputTokens = 10000
|
||||
}
|
||||
};
|
||||
|
||||
var response = await _http.PostAsJsonAsync(
|
||||
$"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={apiKey}",
|
||||
requestBody
|
||||
);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var error = await response.Content.ReadAsStringAsync();
|
||||
throw new Exception($"Gemini API Error: {error}");
|
||||
}
|
||||
|
||||
var jsonString = await response.Content.ReadAsStringAsync();
|
||||
|
||||
using var doc = JsonDocument.Parse(jsonString);
|
||||
|
||||
var text = doc.RootElement
|
||||
.GetProperty("candidates")[0]
|
||||
.GetProperty("content")
|
||||
.GetProperty("parts")[0]
|
||||
.GetProperty("text")
|
||||
.GetString();
|
||||
|
||||
return text ?? throw new Exception("No response text from Gemini.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user