This commit is contained in:
2026-05-06 12:19:31 +03:00
parent 17266730fc
commit 89cb5a10da
34 changed files with 198 additions and 226 deletions
@@ -1,5 +1,5 @@
using Api.Requests;
using Api.Responses;
using Api.Models.Requests;
using Api.Models.Responses;
namespace Api.Services.Contracts;
@@ -1,6 +0,0 @@
namespace Api.Services.Contracts;
public interface IMatcherAiClient
{
Task<string> CreateChatCompletionAsync(string systemPrompt, string userPrompt, decimal temperature, CancellationToken ct);
}
@@ -1,12 +0,0 @@
using Api.Responses;
namespace Api.Services.Contracts;
public interface IMatcherRepository
{
Task InitializeAsync(CancellationToken ct);
Task<JobMatchResponse?> GetMatchAsync(string cvDocumentId, string jobDocumentId, CancellationToken ct);
Task SaveMatchAsync(string cvDocumentId, string jobDocumentId, JobMatchResponse response, CancellationToken ct);
Task<string?> GetChatCompletionAsync(string cacheKey, CancellationToken ct);
Task SaveChatCompletionAsync(string cacheKey, string model, decimal temperature, string responseText, CancellationToken ct);
}
@@ -1,12 +0,0 @@
using Api.Requests;
using Api.Responses;
namespace Api.Services.Contracts;
public interface IRagApiClient
{
Task<RagIndexResponse> IndexCvPdfAsync(IFormFile file, CancellationToken ct);
Task<RagIndexResponse> IndexJobTextAsync(string text, string? url, string? title, CancellationToken ct);
Task<RagDocumentDetails?> GetDocumentAsync(string documentId, CancellationToken ct);
Task<RagSearchResponse> SearchAsync(RagSearchRequest request, CancellationToken ct);
}
+6 -3
View File
@@ -1,8 +1,11 @@
using System.Text.Json;
using Api.Requests;
using Api.Responses;
using Api.Clients.Ai.Contracts;
using Api.Clients.Api.Contracts;
using Api.Data.Repositories.Contracts;
using Api.Models.Requests;
using Api.Models.Responses;
using Api.Models.Settings;
using Api.Services.Contracts;
using Api.Settings;
using Microsoft.Extensions.Options;
namespace Api.Services;
@@ -1,88 +0,0 @@
using System.Text.Json;
using Api.Data;
using Api.Data.Entities;
using Api.Responses;
using Api.Services.Contracts;
using Microsoft.EntityFrameworkCore;
namespace Api.Services;
public sealed class EfMatcherRepository : IMatcherRepository
{
private readonly CvMatcherDbContext _db;
private readonly ILogger<EfMatcherRepository> _logger;
public EfMatcherRepository(CvMatcherDbContext db, ILogger<EfMatcherRepository> logger)
{
_db = db;
_logger = logger;
}
public async Task InitializeAsync(CancellationToken ct)
{
_logger.LogInformation("Ensuring CV matcher database schema exists using EF Core");
await _db.Database.EnsureCreatedAsync(ct);
}
public async Task<JobMatchResponse?> GetMatchAsync(string cvDocumentId, string jobDocumentId, CancellationToken ct)
{
var json = await _db.CvMatchResults
.AsNoTracking()
.Where(x => x.CvDocumentId == cvDocumentId && x.JobDocumentId == jobDocumentId)
.Select(x => x.ResultJson)
.FirstOrDefaultAsync(ct);
if (string.IsNullOrWhiteSpace(json)) return null;
var result = JsonSerializer.Deserialize<JobMatchResponse>(json, new JsonSerializerOptions(JsonSerializerDefaults.Web));
if (result is not null) result.Cached = true;
return result;
}
public async Task SaveMatchAsync(string cvDocumentId, string jobDocumentId, JobMatchResponse response, CancellationToken ct)
{
var exists = await _db.CvMatchResults.AnyAsync(
x => x.CvDocumentId == cvDocumentId && x.JobDocumentId == jobDocumentId,
ct);
if (exists) return;
_db.CvMatchResults.Add(new CvMatchResultEntity
{
Id = Guid.NewGuid().ToString("N"),
CvDocumentId = cvDocumentId,
JobDocumentId = jobDocumentId,
ResultJson = JsonSerializer.Serialize(response, new JsonSerializerOptions(JsonSerializerDefaults.Web)),
Score = response.Score,
CreatedAt = DateTime.UtcNow
});
await _db.SaveChangesAsync(ct);
}
public async Task<string?> GetChatCompletionAsync(string cacheKey, CancellationToken ct)
{
return await _db.CvMatcherChatCache
.AsNoTracking()
.Where(x => x.CacheKey == cacheKey)
.Select(x => x.ResponseText)
.FirstOrDefaultAsync(ct);
}
public async Task SaveChatCompletionAsync(string cacheKey, string model, decimal temperature, string responseText, CancellationToken ct)
{
var exists = await _db.CvMatcherChatCache.AnyAsync(x => x.CacheKey == cacheKey, ct);
if (exists) return;
_db.CvMatcherChatCache.Add(new CvMatcherChatCacheEntity
{
CacheKey = cacheKey,
Model = model,
Temperature = temperature,
ResponseText = responseText,
CreatedAt = DateTime.UtcNow
});
await _db.SaveChangesAsync(ct);
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
using Api.Models.Settings;
using Api.Services.Contracts;
using Api.Settings;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
-13
View File
@@ -1,13 +0,0 @@
using System.Security.Cryptography;
using System.Text;
namespace Api.Services;
public static class HashHelper
{
public static string Compute(string value)
{
using var sha = SHA256.Create();
return Convert.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(value ?? string.Empty)));
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
using System.Net;
using System.Text.RegularExpressions;
using Api.Models.Settings;
using Api.Services.Contracts;
using Api.Settings;
using Microsoft.Extensions.Options;
namespace Api.Services;
@@ -1,95 +0,0 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Api.Services.Contracts;
using Api.Settings;
using Microsoft.Extensions.Options;
namespace Api.Services;
public sealed class MatcherAiClient : IMatcherAiClient
{
private readonly HttpClient _http;
private readonly IMatcherRepository _repository;
private readonly AiSettings _settings;
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public MatcherAiClient(HttpClient http, IMatcherRepository repository, IOptions<AiSettings> options)
{
_http = http;
_repository = repository;
_settings = options.Value;
}
public async Task<string> CreateChatCompletionAsync(string systemPrompt, string userPrompt, decimal temperature, CancellationToken ct)
{
var model = GetModel();
var cacheKey = HashHelper.Compute($"chat:{_settings.Provider}:{model}:{temperature:0.00}:{systemPrompt}:{userPrompt}");
var cached = await _repository.GetChatCompletionAsync(cacheKey, ct);
if (cached is not null) return cached;
var response = IsOllama()
? await CreateOllamaChatCompletionAsync(systemPrompt, userPrompt, temperature, ct)
: await CreateOpenAiChatCompletionAsync(systemPrompt, userPrompt, temperature, ct);
await _repository.SaveChatCompletionAsync(cacheKey, model, temperature, response, ct);
return response;
}
private bool IsOllama() => string.Equals(_settings.Provider, "Ollama", StringComparison.OrdinalIgnoreCase);
private string GetModel() => IsOllama() ? _settings.Ollama.ChatModel : _settings.OpenAI.ChatModel;
private async Task<string> CreateOpenAiChatCompletionAsync(string systemPrompt, string userPrompt, decimal temperature, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(_settings.OpenAI.ApiKey)) throw new InvalidOperationException("OpenAI API key is missing.");
using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/chat/completions");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _settings.OpenAI.ApiKey);
request.Content = ToJson(new
{
model = _settings.OpenAI.ChatModel,
temperature,
response_format = new { type = "json_object" },
messages = new[]
{
new { role = "system", content = systemPrompt },
new { role = "user", content = userPrompt }
}
});
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(15, _settings.OpenAI.TimeoutSeconds)));
using var response = await _http.SendAsync(request, cts.Token);
var json = await response.Content.ReadAsStringAsync(cts.Token);
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"OpenAI chat failed: {(int)response.StatusCode} {json}");
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString() ?? "{}";
}
private async Task<string> CreateOllamaChatCompletionAsync(string systemPrompt, string userPrompt, decimal temperature, CancellationToken ct)
{
var baseUrl = _settings.Ollama.BaseUrl.TrimEnd('/');
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(30, _settings.Ollama.TimeoutSeconds)));
using var response = await _http.PostAsync($"{baseUrl}/api/chat", ToJson(new
{
model = _settings.Ollama.ChatModel,
stream = false,
format = "json",
messages = new[]
{
new { role = "system", content = systemPrompt },
new { role = "user", content = userPrompt }
},
options = new { temperature = (float)temperature }
}), cts.Token);
var json = await response.Content.ReadAsStringAsync(cts.Token);
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"Ollama chat failed: {(int)response.StatusCode} {json}");
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty("message").GetProperty("content").GetString() ?? "{}";
}
private static StringContent ToJson<T>(T payload) => new(JsonSerializer.Serialize(payload, JsonOptions), Encoding.UTF8, "application/json");
}
-80
View File
@@ -1,80 +0,0 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Api.Requests;
using Api.Responses;
using Api.Services.Contracts;
using Api.Settings;
using Microsoft.Extensions.Options;
namespace Api.Services;
public sealed class RagApiClient : IRagApiClient
{
private readonly HttpClient _http;
private readonly RagApiSettings _settings;
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
public RagApiClient(HttpClient http, IOptions<RagApiSettings> options)
{
_http = http;
_settings = options.Value;
_http.BaseAddress = new Uri(_settings.BaseUrl.TrimEnd('/') + "/");
if (!string.IsNullOrWhiteSpace(_settings.InternalApiKey))
{
_http.DefaultRequestHeaders.Add("X-Internal-Api-Key", _settings.InternalApiKey);
}
}
public async Task<RagIndexResponse> IndexCvPdfAsync(IFormFile file, CancellationToken ct)
{
using var content = new MultipartFormDataContent();
await using var stream = file.OpenReadStream();
using var fileContent = new StreamContent(stream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
content.Add(fileContent, "file", file.FileName);
content.Add(new StringContent("cv"), "documentType");
content.Add(new StringContent(file.FileName), "title");
using var response = await _http.PostAsync("api/rag/documents", content, ct);
return await ReadJsonAsync<RagIndexResponse>(response, ct);
}
public async Task<RagIndexResponse> IndexJobTextAsync(string text, string? url, string? title, CancellationToken ct)
{
using var content = new MultipartFormDataContent
{
{ new StringContent(text), "text" },
{ new StringContent("job"), "documentType" },
{ new StringContent(title ?? "Job description"), "title" }
};
if (!string.IsNullOrWhiteSpace(url)) content.Add(new StringContent(url), "sourceUrl");
using var response = await _http.PostAsync("api/rag/documents", content, ct);
return await ReadJsonAsync<RagIndexResponse>(response, ct);
}
public async Task<RagDocumentDetails?> GetDocumentAsync(string documentId, CancellationToken ct)
{
using var response = await _http.GetAsync($"api/rag/documents/{Uri.EscapeDataString(documentId)}", ct);
if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return null;
return await ReadJsonAsync<RagDocumentDetails>(response, ct);
}
public async Task<RagSearchResponse> SearchAsync(RagSearchRequest request, CancellationToken ct)
{
using var response = await _http.PostAsync(
"api/rag/search",
new StringContent(JsonSerializer.Serialize(request, JsonOptions), Encoding.UTF8, "application/json"),
ct);
return await ReadJsonAsync<RagSearchResponse>(response, ct);
}
private static async Task<T> ReadJsonAsync<T>(HttpResponseMessage response, CancellationToken ct)
{
var json = await response.Content.ReadAsStringAsync(ct);
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"RAG API failed: {(int)response.StatusCode} {json}");
}
return JsonSerializer.Deserialize<T>(json, JsonOptions) ?? throw new InvalidOperationException("RAG API returned invalid JSON.");
}
}