Skip to content

Embedding Ownership

Split-Ownership Principle

The Loryth platform has two distinct embedding use cases, owned by different services:

Concern Owner Table Purpose
Conversation vectors loryth-ai ai_conversation_vector Semantic search across chat history
Document vectors loryth-kb kb_document_vector (future) Knowledge base document retrieval

Each service manages its own embedding lifecycle — generation, storage, indexing, and search. The EmbeddingProvider abstraction is shared, but each service calls it independently with its own content.

ai_conversation_vector

Stores one embedding per message for semantic similarity search across conversations.

Column Type Description
id BIGSERIAL Primary key
uuid uuid Unique identifier
message_id BIGINT FK → ai_message.id (CASCADE)
space_id uuid Space for query scoping
conversation_id uuid Conversation UUID for result grouping
embedding_model_ref VARCHAR(255) Model identifier (e.g., text-embedding-ada-002)
content_hash VARCHAR(128) SHA hash of embedded content (dedup)
embedding vector(1536) pgvector column (1536 dimensions)
created_at TIMESTAMP Creation timestamp

Index

CREATE INDEX idx_ai_conversation_vector__embedding
    ON ai_conversation_vector
    USING ivfflat (embedding vector_cosine_ops);

IVFFlat is used for approximate nearest neighbor search with cosine similarity. The index works with any number of rows (including zero).

EmbeddingProvider Abstraction

class EmbeddingProvider(ABC):
    @abstractmethod
    def embed(self, texts: list[str]) -> list[list[float]]:
        """Generate embeddings for a list of texts."""
        ...

Implementations

Provider Dimensions Status
StubEmbeddingProvider 1536 Available (zero vectors, for dev/test)
OpenAI text-embedding-ada-002 1536 Planned
OpenAI text-embedding-3-small 1536 Planned

The dimension count (1536) is fixed in v1 by the vector(1536) column definition. Supporting variable dimensions would require a schema migration.

Embedding Generation Flow

  1. Client calls POST /embeddings/generate with conversation_id
  2. EmbeddingService loads all messages for the conversation
  3. For each message, compute content_hash (SHA-256 of content)
  4. Skip messages that already have a vector with matching content_hash (unless force=true)
  5. Batch remaining texts through EmbeddingProvider.embed()
  6. Store resulting ConversationVector records

Search Flow

  1. Client calls POST /conversations/search with space_id, query, and limit
  2. EmbeddingService embeds the query text via EmbeddingProvider.embed()
  3. Execute pgvector cosine similarity search scoped to space_id:
    SELECT *, 1 - (embedding <=> query_vector) AS similarity
    FROM ai_conversation_vector
    WHERE space_id = :space_id
    ORDER BY embedding <=> query_vector
    LIMIT :limit
    
  4. Return ranked results with conversation_id, message_id, content, and similarity score