178 lines
6.5 KiB
Go
178 lines
6.5 KiB
Go
// Package machinelearning implements the private Pages Machine Learning v1
|
|
// transport. Callers must authorize corpus scope and external transmission,
|
|
// enqueue work, and recheck revision/policy generations before persisting results.
|
|
// This package does not discover documents, retry requests, or change City paths.
|
|
package machinelearning
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const maxBody = 128 * 1024
|
|
const maxResponse = 2 * 1024 * 1024
|
|
|
|
var safeToken = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`)
|
|
var safeID = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`)
|
|
var modelHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
|
|
|
type Input struct {
|
|
ID string `json:"id"`
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
type Request struct {
|
|
Protocol string `json:"protocol"`
|
|
DomainUUID string `json:"domain_uuid"`
|
|
ScopeUUID string `json:"scope_uuid"`
|
|
Provider string `json:"provider"`
|
|
Model string `json:"model"`
|
|
Dimensions int `json:"dimensions"`
|
|
Inputs []Input `json:"inputs"`
|
|
AllowExternal bool `json:"allow_external"`
|
|
}
|
|
|
|
type Output struct {
|
|
ID string `json:"id"`
|
|
InputSHA256 string `json:"input_sha256"`
|
|
Vector []float64 `json:"vector"`
|
|
}
|
|
|
|
type Result struct {
|
|
Protocol string `json:"protocol"`
|
|
DomainUUID string `json:"domain_uuid"`
|
|
ScopeUUID string `json:"scope_uuid"`
|
|
Provider string `json:"provider"`
|
|
Model string `json:"model"`
|
|
ModelRevision string `json:"model_revision"`
|
|
Dimensions int `json:"dimensions"`
|
|
Tokenizer string `json:"tokenizer"`
|
|
Outputs []Output `json:"outputs"`
|
|
Usage struct {
|
|
TotalTokens int64 `json:"total_tokens"`
|
|
} `json:"usage"`
|
|
}
|
|
|
|
// StatusError intentionally excludes the remote response body and request URL.
|
|
// Retry scheduling belongs to Pages; failures can include uncertain API charges.
|
|
type StatusError struct{ Status int }
|
|
|
|
func (e *StatusError) Error() string { return fmt.Sprintf("machine learning HTTP status %d", e.Status) }
|
|
|
|
type Client struct {
|
|
endpoint string
|
|
token string
|
|
http *http.Client
|
|
}
|
|
|
|
// NewClient accepts an operator-configured private service origin, never a
|
|
// document-provided URL. HTTP is for an isolated local network only; use HTTPS
|
|
// and network access control for remote hosts. There is no insecure TLS option.
|
|
func NewClient(origin, token string) (*Client, error) {
|
|
u, err := url.Parse(origin)
|
|
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || !safeToken.MatchString(token) {
|
|
return nil, errors.New("invalid machine learning service configuration")
|
|
}
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
transport.Proxy = nil // Do not leak the private shared token to an env proxy.
|
|
return &Client{endpoint: strings.TrimSuffix(origin, "/") + "/v1/embeddings", token: token,
|
|
http: &http.Client{Transport: transport, Timeout: 40 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
|
|
}
|
|
|
|
func validUUID(s string) bool { id, err := uuid.Parse(s); return err == nil && id.String() == s }
|
|
|
|
func validate(req Request) error {
|
|
if req.Protocol != "1" || !validUUID(req.DomainUUID) || !validUUID(req.ScopeUUID) || req.Dimensions < 1 || req.Dimensions > 1536 || len(req.Inputs) < 1 || len(req.Inputs) > 16 {
|
|
return errors.New("invalid machine learning request")
|
|
}
|
|
if req.Provider == "openai" {
|
|
if !req.AllowExternal || req.Model != "text-embedding-3-small" {
|
|
return errors.New("external embeddings not permitted or unsupported model")
|
|
}
|
|
} else if req.Provider != "doc2vec" || !modelHash.MatchString(req.Model) {
|
|
return errors.New("invalid machine learning provider/model")
|
|
}
|
|
seen := make(map[string]bool)
|
|
for _, input := range req.Inputs {
|
|
if !safeID.MatchString(input.ID) || seen[input.ID] || strings.TrimSpace(input.Text) == "" || !utf8.ValidString(input.Text) || len(input.Text) > 6000 {
|
|
return errors.New("invalid machine learning input")
|
|
}
|
|
seen[input.ID] = true
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) Embed(ctx context.Context, input Request) (*Result, error) {
|
|
if err := validate(input); err != nil {
|
|
return nil, err
|
|
}
|
|
body, err := json.Marshal(input)
|
|
if err != nil || len(body) > maxBody {
|
|
return nil, errors.New("machine learning input too large")
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body))
|
|
if err != nil {
|
|
return nil, errors.New("machine learning request failed")
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
|
response, err := c.http.Do(req)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return nil, ctx.Err()
|
|
}
|
|
return nil, errors.New("machine learning transport failed")
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
return nil, &StatusError{Status: response.StatusCode}
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(response.Body, maxResponse+1))
|
|
if err != nil || len(raw) > maxResponse {
|
|
return nil, errors.New("invalid machine learning response")
|
|
}
|
|
var result Result
|
|
if json.Unmarshal(raw, &result) != nil || result.Protocol != input.Protocol || result.DomainUUID != input.DomainUUID || result.ScopeUUID != input.ScopeUUID || result.Provider != input.Provider || result.Model != input.Model || result.ModelRevision != input.Model || result.Dimensions != input.Dimensions || len(result.Outputs) != len(input.Inputs) || result.Usage.TotalTokens < 0 {
|
|
return nil, errors.New("machine learning result metadata mismatch")
|
|
}
|
|
expectedTokenizer := "provider"
|
|
if input.Provider == "doc2vec" {
|
|
expectedTokenizer = "unicode-cjk-bigram-v1"
|
|
}
|
|
if result.Tokenizer != expectedTokenizer {
|
|
return nil, errors.New("machine learning tokenizer mismatch")
|
|
}
|
|
for i, output := range result.Outputs {
|
|
hash := sha256.Sum256([]byte(input.Inputs[i].Text))
|
|
if output.ID != input.Inputs[i].ID || output.InputSHA256 != hex.EncodeToString(hash[:]) || len(output.Vector) != input.Dimensions {
|
|
return nil, errors.New("machine learning output mismatch")
|
|
}
|
|
nonzero := false
|
|
for _, value := range output.Vector {
|
|
if math.IsNaN(value) || math.IsInf(value, 0) {
|
|
return nil, errors.New("non-finite machine learning vector")
|
|
}
|
|
nonzero = nonzero || value != 0
|
|
}
|
|
if !nonzero {
|
|
return nil, errors.New("empty machine learning vector")
|
|
}
|
|
}
|
|
return &result, nil
|
|
}
|