75 fichiers, ~1 mois de travail depuis f222861 (17/07). Contenu :
Onboarding self-service — jamais exécuté de bout en bout
OnboardingController, StripeWebhookController, StripeService, ResendEmailService
+ IEmailService (10 templates), EmailTemplates/, TrialLifecycleService (Hangfire),
PasswordTokenHelper, SlugHelper, 5 DTOs. Essai 14 j, Stripe customer/Checkout/Tax,
mot de passe oublié + invitation user, plafond IA d'essai.
Schéma Postgres v3 — passe pendant que la base est vide
ContentEmbedding + index HNSW (vector_cosine_ops), IEmbeddingService +
GoogleEmbeddingService (gemini-embedding-001, 768 dims), Deployment/Dockerfile.postgres
(postgis 3.4.3 + pgvector 0.8.6, épinglé par digest — un tag mobile rejouerait le
warning de collation glibc). Colonnes Resource : StoragePath, FileName,
IncludeInAiKnowledge, AiIndexStatus + nouveaux ResourceType ajoutés EN FIN d'enum.
Guide IA
Champs Guide* sur Instance + InstanceDTO, AssistantService lit la configuration client
dans les 4 blocs de prompt (ton codé en dur retiré, règle hors-sujet ajoutée aux deux
variantes qui n'en avaient pas), IHttpClientFactory à la place des new HttpClient().
Table VisitorQuestion + ConversationId sur AiChatRequest.
Stats
Rétention unifiée à 13 mois (instances ET plans), VisitEventPurgeService.
Nettoyage
IsStepLocked / IsHiddenInitially / FactContent supprimés de GuidedStep — IsStepLocked
rendait une étape définitivement infranchissable même après réussite.
SectionMap allégé (-57 lignes).
Tests
SectionParcoursControllerTests, FakeConfiguration, FakeEmailService.
ContentEmbedding a cassé 116 tests sur 124 (EF InMemory ne connaît pas Vector) :
l'entité est exclue quand le provider n'est pas Npgsql. Conséquence assumée —
le vector store n'est couvert par aucun test. dotnet test 124/124.
10 migrations EF. Base locale à jour, dotnet build 0 erreur.
Rien n'est en prod : la bascule Mongo → Postgres est décrite dans DOCS/STATUS.md §1quinquies.
⚠️ appsettings.json contient les clés Stripe (test) et Resend (prod) en clair — à rotationner.
153 lines
5.8 KiB
C#
153 lines
5.8 KiB
C#
using ManagerService.Data;
|
|
using Microsoft.Extensions.Configuration;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ManagerService.Services
|
|
{
|
|
/// <summary>
|
|
/// Embeddings via l'endpoint OpenAI-compatible de Google — même hôte et même clé
|
|
/// que le chat (voir Startup), donc aucune configuration supplémentaire.
|
|
/// </summary>
|
|
public class GoogleEmbeddingService : IEmbeddingService
|
|
{
|
|
private const string Model = "gemini-embedding-001";
|
|
private const string Endpoint = "https://generativelanguage.googleapis.com/v1beta/openai/embeddings";
|
|
|
|
/// <summary>
|
|
/// L'API accepte des lots plus gros, mais un lot trop large fait échouer les ~150 morceaux
|
|
/// d'un document d'un coup sur un seul dépassement de limite de jetons.
|
|
/// </summary>
|
|
private const int BatchSize = 50;
|
|
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
private readonly string _apiKey;
|
|
|
|
public int Dimensions => ContentEmbedding.Dimensions;
|
|
|
|
public GoogleEmbeddingService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
|
|
{
|
|
_httpClientFactory = httpClientFactory;
|
|
_apiKey = configuration["AI:ApiKey"];
|
|
}
|
|
|
|
public async Task<float[]> EmbedAsync(string text, CancellationToken cancellationToken = default)
|
|
{
|
|
var result = await EmbedBatchAsync(new[] { text }, cancellationToken);
|
|
return result[0];
|
|
}
|
|
|
|
public async Task<IReadOnlyList<float[]>> EmbedBatchAsync(IReadOnlyList<string> texts, CancellationToken cancellationToken = default)
|
|
{
|
|
if (texts == null || texts.Count == 0)
|
|
return Array.Empty<float[]>();
|
|
|
|
var results = new List<float[]>(texts.Count);
|
|
|
|
for (var offset = 0; offset < texts.Count; offset += BatchSize)
|
|
{
|
|
var batch = texts.Skip(offset).Take(BatchSize).ToArray();
|
|
results.AddRange(await EmbedOneBatchAsync(batch, cancellationToken));
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
private async Task<List<float[]>> EmbedOneBatchAsync(string[] batch, CancellationToken cancellationToken)
|
|
{
|
|
var client = _httpClientFactory.CreateClient();
|
|
client.DefaultRequestHeaders.Authorization =
|
|
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _apiKey);
|
|
|
|
// dimensions est obligatoire : le modèle renvoie 3072 valeurs par défaut,
|
|
// ce que la colonne vector(768) refuserait.
|
|
var payload = new EmbeddingRequest
|
|
{
|
|
Model = Model,
|
|
Input = batch,
|
|
Dimensions = Dimensions
|
|
};
|
|
|
|
var response = await client.PostAsJsonAsync(Endpoint, payload, cancellationToken);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
var body = await response.Content.ReadAsStringAsync(cancellationToken);
|
|
throw new InvalidOperationException(
|
|
$"Embedding API error ({(int)response.StatusCode}): {body}");
|
|
}
|
|
|
|
var parsed = await response.Content.ReadFromJsonAsync<EmbeddingResponse>(cancellationToken: cancellationToken);
|
|
|
|
if (parsed?.Data == null || parsed.Data.Count != batch.Length)
|
|
throw new InvalidOperationException(
|
|
$"Embedding API returned {parsed?.Data?.Count ?? 0} vectors for {batch.Length} texts.");
|
|
|
|
// Vérifié le 2026-08-09 : Google ne renvoie pas le champ "index" du contrat
|
|
// OpenAI — chaque item ne porte que "embedding" et "object". Trier dessus
|
|
// donnerait un tri sur des zéros. L'ordre du tableau suit celui des entrées.
|
|
return parsed.Data
|
|
.Select(d => Normalize(d.Embedding))
|
|
.ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Normalise le vecteur en norme L2.
|
|
/// gemini-embedding-001 ne renvoie des vecteurs normalisés que sur sa dimension
|
|
/// native (3072). Toute dimension réduite sort brute, et la distance cosinus
|
|
/// de pgvector suppose des vecteurs normalisés — sans ça, le classement des
|
|
/// résultats est faussé sans qu'aucune erreur ne soit levée.
|
|
/// </summary>
|
|
private float[] Normalize(float[] vector)
|
|
{
|
|
if (vector == null || vector.Length != Dimensions)
|
|
throw new InvalidOperationException(
|
|
$"Embedding API returned {vector?.Length ?? 0} dimensions, expected {Dimensions}.");
|
|
|
|
double sumOfSquares = 0;
|
|
foreach (var value in vector)
|
|
sumOfSquares += (double)value * value;
|
|
|
|
var norm = Math.Sqrt(sumOfSquares);
|
|
if (norm == 0)
|
|
return vector;
|
|
|
|
var normalized = new float[vector.Length];
|
|
for (var i = 0; i < vector.Length; i++)
|
|
normalized[i] = (float)(vector[i] / norm);
|
|
|
|
return normalized;
|
|
}
|
|
|
|
private class EmbeddingRequest
|
|
{
|
|
[JsonPropertyName("model")]
|
|
public string Model { get; set; }
|
|
|
|
[JsonPropertyName("input")]
|
|
public string[] Input { get; set; }
|
|
|
|
[JsonPropertyName("dimensions")]
|
|
public int Dimensions { get; set; }
|
|
}
|
|
|
|
private class EmbeddingResponse
|
|
{
|
|
[JsonPropertyName("data")]
|
|
public List<EmbeddingData> Data { get; set; }
|
|
}
|
|
|
|
private class EmbeddingData
|
|
{
|
|
[JsonPropertyName("embedding")]
|
|
public float[] Embedding { get; set; }
|
|
}
|
|
}
|
|
}
|