Charan S commited on
Commit ·
eae9e17
1
Parent(s): fac1a55
Fix: init_embeddings no-op (async-safe)
Browse filesFiles changed (6)
123456# LLM — OpenAI (required)OPENAI_API_KEY=sk-...# Voice pipeline — LiveKit Cloud (required)# Free tier: 5,000 WebRTC min/mo — https://cloud.livekit.ioLIVEKIT_URL=wss://your-project.livekit.cloud12345678910# 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.cloud
6 unmodified lines78910111213141516171819202122236 unmodified linesWORKDIR /appCOPY 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/cpuRUN pip install --no-cache-dir -r requirements.txtCOPY . .# 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 78606 unmodified lines789101112131415166 unmodified linesWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .# HuggingFace Spaces routes external traffic to port 7860EXPOSE 7860
4 unmodified lines56789104 unmodified linesmodel_config = SettingsConfigDict(env_file=".env", extra="ignore")openai_api_key: str = ""# LiveKitlivekit_url: str = ""4 unmodified lines5678910114 unmodified linesmodel_config = SettingsConfigDict(env_file=".env", extra="ignore")openai_api_key: str = ""hf_token: str = "" # HuggingFace token — used for Inference API embeddings# LiveKitlivekit_url: str = ""
1234567891011121314151617181920212223242526272829303132333435363738394041424344"""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."""import asyncioimport functoolsimport loggingfrom typing import Optionallogger = logging.getLogger(__name__)_model = NoneEMBED_MODEL = "all-MiniLM-L6-v2"EMBED_DIM = 384def init_embeddings(_openai_client=None) -> None:"""Load the local model once at startup. Signature compatible with old init_embeddings(openai_client)."""global _modelfrom sentence_transformers import SentenceTransformerlogger.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)")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")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 def embed_single(text: str) -> list[float]:"""Embed a single text string."""results = await embed_texts([text])return results[0]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""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 loggingimport httpxfrom config import settingslogger = logging.getLogger(__name__)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:"""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 via HF Inference API. Returns list of 384-dim vectors."""if not texts:return []async with httpx.AsyncClient(timeout=20.0) as client:return await _embed_via_api(texts, client)async def embed_single(text: str) -> list[float]: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 responseif result and isinstance(result[0][0], list):result = [row[0] for row in result]return result
14 unmodified lines1516171819202114 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# Auth14 unmodified lines15161718192014 unmodified linesdateparser>=1.2.0python-multipart==0.0.28rank-bm25==0.2.2# LiveKit Agents voice pipeline (replaces Pipecat)livekit-agents[deepgram,openai,silero,turn-detector,cartesia]~=1.5# Auth
11 unmodified lines1213141516171811 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 localhostexport BACKEND_INTERNAL_URL=${BACKEND_INTERNAL_URL:-http://localhost:7860}echo "▶ Running database migrations..."11 unmodified lines1213141516171811 unmodified linesmkdir -p /data/chroma_dbexport CHROMA_PERSIST_DIR=${CHROMA_PERSIST_DIR:-/data/chroma_db}# 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