37 lines
1.2 KiB
C#
37 lines
1.2 KiB
C#
using System.Net.Http.Json;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace GymLogAI.AI;
|
|
|
|
public sealed class OpenRouterChatClient(
|
|
HttpClient httpClient,
|
|
IOptions<OpenRouterOptions> options,
|
|
ILogger<OpenRouterChatClient> logger)
|
|
{
|
|
private readonly OpenRouterOptions _options = options.Value;
|
|
|
|
public async Task<string?> CompleteAsync(string prompt, CancellationToken cancellationToken)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(_options.ApiKey))
|
|
{
|
|
logger.LogInformation("OpenRouter API key is not configured. Returning stubbed chat completion.");
|
|
return null;
|
|
}
|
|
|
|
using var request = new HttpRequestMessage(HttpMethod.Post, "chat/completions")
|
|
{
|
|
Content = JsonContent.Create(new
|
|
{
|
|
model = _options.ChatModel,
|
|
messages = new[] { new { role = "user", content = prompt } }
|
|
})
|
|
};
|
|
|
|
request.Headers.Authorization = new("Bearer", _options.ApiKey);
|
|
var response = await httpClient.SendAsync(request, cancellationToken);
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadAsStringAsync(cancellationToken);
|
|
}
|
|
}
|