Charan S commited on
Commit Β·
eae9e17
1
Parent(s): fac1a55
Fix: init_embeddings no-op (async-safe)
Browse filesFiles changed (6)
12345678910# LLM β OpenAI (required)OPENAI_API_KEY=sk-...
# HuggingFace β used for embeddings via Inference API (sentence-transformers/all-MiniLM-L6-v2)# Free tier works without a token but is rate-limited. Get one at huggingface.co/settings/tokensHF_TOKEN=hf_...
# Voice pipeline β LiveKit Cloud (required)# Free tier: 5,000 WebRTC min/mo β https://cloud.livekit.ioLIVEKIT_URL=wss://your-project.livekit.cloud6 unmodified lines78910111213101112131819201415166 unmodified linesWORKDIR /app
COPY requirements.txt .
# CPU-only PyTorch β avoids pulling 2 GB of CUDA wheelsRUN pip install --no-cache-dir torch --extra-index-url https://download.pytorch.org/whl/cpu
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Bake the embedding model into the image so first KB query has zero cold-startRUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')"
# HuggingFace Spaces routes external traffic to port 7860EXPOSE 7860
4 unmodified lines5678910114 unmodified lines model_config = SettingsConfigDict(env_file=".env", extra="ignore")
openai_api_key: str = "" hf_token: str = "" # HuggingFace token β used for Inference API embeddings
# LiveKit livekit_url: str = ""12342346759678910111213141314151617181920212223241920212223282930242526333435363738272829303142323334353637383940414243444546474849505152"""Local embeddings via sentence-transformers all-MiniLM-L6-v2.Zero API cost. 384-dim vectors. Runs on CPU in a thread pool so theasync event loop is never blocked.Embeddings via HuggingFace Inference API β sentence-transformers/all-MiniLM-L6-v2.384-dim vectors. Zero local GPU/CPU cost. Model is already hosted on HuggingFace."""import asyncioimport functoolsimport loggingfrom typing import Optional
import httpx
from config import settings
logger = logging.getLogger(__name__)
_model = NoneEMBED_MODEL = "all-MiniLM-L6-v2"EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"EMBED_DIM = 384_HF_API_URL = f"https://api-inference.huggingface.co/pipeline/feature-extraction/{EMBED_MODEL}"
def init_embeddings(_openai_client=None) -> None: """Load the local model once at startup. Signature compatible with old init_embeddings(openai_client).""" global _model from sentence_transformers import SentenceTransformer logger.info(f"Loading local embedding model: {EMBED_MODEL}") _model = SentenceTransformer(EMBED_MODEL) logger.info(f"Embeddings initialized: {EMBED_MODEL} ({EMBED_DIM}-dim, local, zero API cost)") """No-op β embeddings are served by HF Inference API, always ready.""" logger.info("Embeddings ready: %s (HuggingFace Inference API)", EMBED_MODEL)
async def embed_texts(texts: list[str]) -> list[list[float]]: """Embed a batch of texts. Returns list of float vectors. Non-blocking.""" if not _model: raise RuntimeError("embeddings not initialized β call init_embeddings() first") """Embed a batch of texts via HF Inference API. Returns list of 384-dim vectors.""" if not texts: return [] loop = asyncio.get_event_loop() vectors = await loop.run_in_executor( None, functools.partial(_model.encode, texts, convert_to_numpy=True, show_progress_bar=False) ) return vectors.tolist() async with httpx.AsyncClient(timeout=20.0) as client: return await _embed_via_api(texts, client)
async def embed_single(text: str) -> list[float]: """Embed a single text string.""" results = await embed_texts([text]) return results[0]
async def _embed_via_api(texts: list[str], client: httpx.AsyncClient) -> list[list[float]]: headers = {"Content-Type": "application/json"} if settings.hf_token: headers["Authorization"] = f"Bearer {settings.hf_token}"
resp = await client.post( _HF_API_URL, headers=headers, json={"inputs": texts}, ) resp.raise_for_status() result = resp.json()
# HF returns shape [n, dim] for batch β normalise any 3-D response if result and isinstance(result[0][0], list): result = [row[0] for row in result] return result14 unmodified lines1516171818192014 unmodified linesdateparser>=1.2.0python-multipart==0.0.28rank-bm25==0.2.2sentence-transformers==3.3.1# LiveKit Agents voice pipeline (replaces Pipecat)livekit-agents[deepgram,openai,silero,turn-detector,cartesia]~=1.5# Auth11 unmodified lines121314151516171811 unmodified linesmkdir -p /data/chroma_dbexport CHROMA_PERSIST_DIR=${CHROMA_PERSIST_DIR:-/data/chroma_db}
# Both processes run in this container β worker calls /api/kb/search on localhost# Both processes share this container β worker calls /api/kb/search on localhostexport BACKEND_INTERNAL_URL=${BACKEND_INTERNAL_URL:-http://localhost:7860}
echo "βΆ Running database migrations...".env.example+4
Dockerfile-7
config.py+1
knowledge/embeddings.py+32-24
requirements.txt-1
start.sh+1-1