feat(customer1): add pgvector RAG knowledge base with embedding service
- Custom PostgreSQL 15.2 image with pgvector 0.8.0 extension - Updated pg-cluster-hermes.yaml: custom image, sharedPreloadLibraries, maintenance_work_mem - RAG schema: documents table with vector(768) embeddings + HNSW index - RAG init job: ConfigMap + Job to apply schema to agent_memory db - Embedding service: FastAPI with nomic-embed-text-v1.5 - OpenAI-compatible /v1/embeddings endpoint - Deployment (1 replica, 2Gi-4Gi memory) + Service manifests - Updated kustomization.yaml to include new resources
This commit is contained in:
parent
99a864171b
commit
4df7450461
13 changed files with 463 additions and 1 deletions
18
apps/base/customer1/embedding-service/Dockerfile.embedding
Normal file
18
apps/base/customer1/embedding-service/Dockerfile.embedding
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install sentence-transformers and deps
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application
|
||||
COPY app.py .
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
|
||||
150
apps/base/customer1/embedding-service/app.py
Normal file
150
apps/base/customer1/embedding-service/app.py
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
"""
|
||||
Lightweight embedding service wrapping nomic-embed-text-v1.5
|
||||
OpenAI-compatible /v1/embeddings endpoint.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# Model globals (loaded at startup)
|
||||
_model = None
|
||||
_tokenizer = None
|
||||
_dimensions = 768 # nomic-embed-text-v1.5 output dimensions
|
||||
_model_name = "nomic-embed-text-v1.5"
|
||||
|
||||
|
||||
def load_model():
|
||||
"""Load the embedding model at startup."""
|
||||
global _model, _tokenizer
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
model_path = os.getenv("MODEL_PATH", _model_name)
|
||||
print(f"Loading model: {model_path}")
|
||||
_model = SentenceTransformer(model_path, device="cpu")
|
||||
_model.max_seq_length = 8192 # nomic supports long contexts
|
||||
print(f"Model loaded. Dimensions: {_model.get_sentence_embedding_dimension()}")
|
||||
_dimensions = _model.get_sentence_embedding_dimension()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Startup: load model."""
|
||||
load_model()
|
||||
yield
|
||||
# Shutdown: no cleanup needed for CPU model
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Embedding Service",
|
||||
description="OpenAI-compatible embedding service using nomic-embed-text-v1.5",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
# --- Request/Response Models ---
|
||||
|
||||
class EmbeddingInput(BaseModel):
|
||||
input: str | list[str] = Field(..., description="Text to embed. Can be a string or list of strings.")
|
||||
model: str = Field(default=_model_name, description="Model name. Only nomic-embed-text-v1.5 is supported.")
|
||||
encoding_format: str = Field(default="float", description="Output format. Only 'float' is supported.")
|
||||
|
||||
|
||||
class EmbeddingObject(BaseModel):
|
||||
object: str = "embedding"
|
||||
embedding: list[float]
|
||||
index: int
|
||||
|
||||
|
||||
class UsageInfo(BaseModel):
|
||||
prompt_tokens: int
|
||||
total_tokens: int
|
||||
|
||||
|
||||
class EmbeddingResponse(BaseModel):
|
||||
object: str = "list"
|
||||
data: list[EmbeddingObject]
|
||||
model: str
|
||||
usage: UsageInfo
|
||||
|
||||
|
||||
# --- Endpoints ---
|
||||
|
||||
@app.post("/v1/embeddings")
|
||||
def create_embeddings(req: EmbeddingInput) -> EmbeddingResponse:
|
||||
"""Create embeddings for input text(s). OpenAI-compatible."""
|
||||
# Normalize input to list
|
||||
if isinstance(req.input, str):
|
||||
texts = [req.input]
|
||||
else:
|
||||
texts = req.input
|
||||
|
||||
if not texts:
|
||||
raise HTTPException(status_code=400, detail="Input must not be empty.")
|
||||
|
||||
if len(texts) > 2048:
|
||||
raise HTTPException(status_code=400, detail="Input must have at most 2048 elements.")
|
||||
|
||||
# Generate embeddings
|
||||
start = time.time()
|
||||
embeddings = _model.encode(
|
||||
texts,
|
||||
normalize_embeddings=True, # cosine similarity ready
|
||||
show_progress_bar=False,
|
||||
).tolist()
|
||||
|
||||
elapsed = time.time() - start
|
||||
|
||||
# Build response
|
||||
data = []
|
||||
total_tokens = 0
|
||||
for i, (text, emb) in enumerate(zip(texts, embeddings)):
|
||||
tokens = len(text.split()) # rough token count
|
||||
total_tokens += tokens
|
||||
data.append(EmbeddingObject(
|
||||
object="embedding",
|
||||
embedding=emb,
|
||||
index=i,
|
||||
))
|
||||
|
||||
return EmbeddingResponse(
|
||||
object="list",
|
||||
data=data,
|
||||
model=req.model,
|
||||
usage=UsageInfo(
|
||||
prompt_tokens=total_tokens,
|
||||
total_tokens=total_tokens,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/v1/models")
|
||||
def list_models():
|
||||
"""List available models. OpenAI-compatible."""
|
||||
return {
|
||||
"object": "list",
|
||||
"data": [
|
||||
{
|
||||
"id": _model_name,
|
||||
"object": "model",
|
||||
"created": int(time.time()),
|
||||
"owned_by": "self",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
"""Health check."""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"model": _model_name,
|
||||
"dimensions": _dimensions,
|
||||
"ready": _model is not None,
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: embedding-service
|
||||
namespace: customer1
|
||||
labels:
|
||||
app: embedding-service
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: embedding-service
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: embedding-service
|
||||
spec:
|
||||
containers:
|
||||
- name: embedding-service
|
||||
image: gcr.io/devops-lab-cluster/embedding-service:1.0.0
|
||||
ports:
|
||||
- containerPort: 8000
|
||||
name: http
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: MODEL_NAME
|
||||
value: "nomic-embed-text-v1.5"
|
||||
resources:
|
||||
requests:
|
||||
cpu: "500m"
|
||||
memory: "2Gi"
|
||||
limits:
|
||||
cpu: "2000m"
|
||||
memory: "4Gi"
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: 8000
|
||||
initialDelaySeconds: 60
|
||||
periodSeconds: 10
|
||||
failureThreshold: 12
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: 8000
|
||||
initialDelaySeconds: 180
|
||||
periodSeconds: 30
|
||||
failureThreshold: 3
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: 8000
|
||||
initialDelaySeconds: 60
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
7
apps/base/customer1/embedding-service/requirements.txt
Normal file
7
apps/base/customer1/embedding-service/requirements.txt
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
fastapi==0.115.0
|
||||
uvicorn[standard]==0.32.0
|
||||
sentence-transformers==3.3.0
|
||||
torch==2.5.1
|
||||
transformers==4.46.0
|
||||
numpy==2.1.0
|
||||
pydantic==2.10.0
|
||||
Loading…
Reference in a new issue