feat(matching): rank with semantic embeddings and explain matches by evidence
This commit is contained in:
1 parent
facc1789b1
commit
24b64d698a
215 files changed
+16951
-327
No files matched your search
@@ -0,0 +1,228 @@
|
||||
// Package ml is the client of the internal ML service. The generated ogen
|
||||
// client in ./api carries the contract; this adapter adds the request
|
||||
// timeout, a response size cap, a circuit breaker, batching, and the checks
|
||||
// that turn the response into domain vectors.
|
||||
package ml
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/ml/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxResponseBytes caps one response: 32 vectors of 4096 floats as JSON
|
||||
// stay far below it.
|
||||
maxResponseBytes = 16 << 20
|
||||
// maxTextRunes is the contract bound of one text; longer texts are cut
|
||||
// before they are sent, the model truncates at its token limit anyway.
|
||||
maxTextRunes = 8000
|
||||
)
|
||||
|
||||
// Settings configure the client.
|
||||
type Settings struct {
|
||||
// BaseURL is the ML service origin, for example http://ml:8000.
|
||||
BaseURL string
|
||||
// Timeout bounds one HTTP request.
|
||||
Timeout time.Duration
|
||||
// FailureThreshold consecutive failures open the circuit for OpenDuration.
|
||||
FailureThreshold int
|
||||
OpenDuration time.Duration
|
||||
}
|
||||
|
||||
// Embedder implements outbound.TextEmbedder over HTTP.
|
||||
type Embedder struct {
|
||||
client *api.Client
|
||||
breaker *breaker
|
||||
}
|
||||
|
||||
var _ outbound.TextEmbedder = (*Embedder)(nil)
|
||||
|
||||
// NewEmbedder validates the settings and builds the client. Nothing connects.
|
||||
func NewEmbedder(settings Settings, clock func() time.Time) (*Embedder, error) {
|
||||
const location = "ml.NewEmbedder"
|
||||
parsed, err := url.Parse(settings.BaseURL)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.User != nil {
|
||||
return nil, errors.New(location + " - ML service URL must be an http or https origin without credentials")
|
||||
}
|
||||
if settings.Timeout <= 0 || settings.FailureThreshold < 1 || settings.OpenDuration <= 0 || clock == nil {
|
||||
return nil, errors.New(location + " - timeout, failure threshold, open duration, and clock must be set")
|
||||
}
|
||||
httpClient := &http.Client{
|
||||
Timeout: settings.Timeout,
|
||||
Transport: limitedTransport{next: http.DefaultTransport},
|
||||
// The service is a fixed internal origin; a redirect is never expected.
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
client, err := api.NewClient(parsed.String(), api.WithClient(httpClient))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - create client: %w", location, err)
|
||||
}
|
||||
return &Embedder{
|
||||
client: client,
|
||||
breaker: &breaker{threshold: settings.FailureThreshold, open: settings.OpenDuration, clock: clock},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Embed encodes texts with the named model in contract-sized batches and
|
||||
// checks that every batch came from the same model. The caller compares the
|
||||
// returned identity with the one it expects.
|
||||
func (embedder *Embedder) Embed(
|
||||
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
|
||||
) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
const location = "ml.Embedder.Embed"
|
||||
var model domain.SemanticModel
|
||||
vectors := make([]domain.SemanticVector, 0, len(texts))
|
||||
for start := 0; start < len(texts); start += outbound.MaxEmbeddingBatch {
|
||||
end := min(start+outbound.MaxEmbeddingBatch, len(texts))
|
||||
batchModel, batch, err := embedder.embedBatch(ctx, modelID, kind, texts[start:end])
|
||||
if err != nil {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("%s - encode batch: %w", location, err)
|
||||
}
|
||||
if start > 0 && batchModel != model {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("%s - the model changed between batches: %w", location, outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
model = batchModel
|
||||
vectors = append(vectors, batch...)
|
||||
}
|
||||
return model, vectors, nil
|
||||
}
|
||||
|
||||
func (embedder *Embedder) embedBatch(
|
||||
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
|
||||
) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
if len(texts) == 0 {
|
||||
return domain.SemanticModel{}, nil, nil
|
||||
}
|
||||
if !embedder.breaker.allow() {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("circuit is open: %w", outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
request := &api.EmbeddingRequest{
|
||||
Model: api.NewOptString(modelID), Kind: api.EmbeddingInputKind(kind), Texts: make([]api.EmbeddingText, 0, len(texts)),
|
||||
}
|
||||
for _, text := range texts {
|
||||
request.Texts = append(request.Texts, api.EmbeddingText(cutRunes(text, maxTextRunes)))
|
||||
}
|
||||
result, err := embedder.client.CreateMLEmbeddings(ctx, request)
|
||||
if err != nil {
|
||||
embedder.breaker.failure()
|
||||
// The client error can quote the URL but never the request body.
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("call the ML service: %w", outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
switch response := result.(type) {
|
||||
case *api.EmbeddingResponse:
|
||||
model, vectors, err := decodeResponse(response, kind, len(texts))
|
||||
if err != nil {
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, err
|
||||
}
|
||||
embedder.breaker.success()
|
||||
return model, vectors, nil
|
||||
case *api.CreateMLEmbeddingsServiceUnavailable:
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
|
||||
default:
|
||||
// 400 or 413: the request breaks the contract or names a model the
|
||||
// service does not serve, and a repeat cannot fix it.
|
||||
embedder.breaker.success()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service refused the request: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeResponse(response *api.EmbeddingResponse, kind outbound.EmbeddingKind, count int) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
model := domain.SemanticModel{
|
||||
ID: response.Model.ID, Revision: response.Model.Revision, PromptVersion: response.Model.PromptVersion,
|
||||
}
|
||||
if err := model.Validate(); err != nil || string(response.Kind) != string(kind) || len(response.Vectors) != count {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the response does not match the request: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vectors := make([]domain.SemanticVector, 0, count)
|
||||
for _, raw := range response.Vectors {
|
||||
if len(raw) != int(response.Model.Dimension) {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("a vector has the wrong dimension: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vector, err := domain.NewSemanticVector(raw)
|
||||
if err != nil {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("a vector is invalid: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vectors = append(vectors, vector)
|
||||
}
|
||||
return model, vectors, nil
|
||||
}
|
||||
|
||||
func cutRunes(text string, limit int) string {
|
||||
runes := []rune(text)
|
||||
if len(runes) <= limit {
|
||||
return text
|
||||
}
|
||||
return string(runes[:limit])
|
||||
}
|
||||
|
||||
// limitedTransport caps the bytes read from a response body.
|
||||
type limitedTransport struct {
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (transport limitedTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
response, err := transport.next.RoundTrip(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Body = limitedBody{Reader: io.LimitReader(response.Body, maxResponseBytes), Closer: response.Body}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
type limitedBody struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}
|
||||
|
||||
// breaker opens after threshold consecutive failures and lets one probe
|
||||
// through after the open duration; a success closes it.
|
||||
type breaker struct {
|
||||
mutex sync.Mutex
|
||||
threshold int
|
||||
open time.Duration
|
||||
clock func() time.Time
|
||||
failures int
|
||||
openUntil time.Time
|
||||
probing bool
|
||||
}
|
||||
|
||||
func (circuit *breaker) allow() bool {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
if circuit.failures < circuit.threshold {
|
||||
return true
|
||||
}
|
||||
if circuit.clock().Before(circuit.openUntil) || circuit.probing {
|
||||
return false
|
||||
}
|
||||
circuit.probing = true
|
||||
return true
|
||||
}
|
||||
|
||||
func (circuit *breaker) success() {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
circuit.failures, circuit.probing = 0, false
|
||||
}
|
||||
|
||||
func (circuit *breaker) failure() {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
circuit.failures++
|
||||
circuit.probing = false
|
||||
if circuit.failures >= circuit.threshold {
|
||||
circuit.openUntil = circuit.clock().Add(circuit.open)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user