How myeolinmalchi/bge-m3-fastapi works
Project type and purpose
• This is a Python-based backend service built with FastAPI (“main.py”) that exposes an embedding API. It uses ONNX Runtime (CPU or CUDA) or llama-cpp under the hood to compute text embeddings. It can be driven via a CLI (“cli.py”) or run as a Docker container via Docker Compose.
File structure
• Top-level scripts:
• main.py – starts the FastAPI app and wires up command-line args for device and batch size.
• cli.py – optional command-line client to call the embedding endpoint (or directly run embedding).
• models/ – directory where you place your model.onnx and model.onnx.data files.
• schemas/ – Pydantic request/response models (schemas/embed.py).
• utils/embed/ – “strategy” packages for different embedders:
• onnx/ (cpu.py, cuda.py inheriting from base)
• llama_cpp/ (embedder.py, session.py)
• base.py for shared interface.
• utils/preprocess/ – text and HTML cleaning modules.
• utils/logger.py and utils/mixins/singleton.py – cross-cutting utilities.
• test.py – simple smoke/test script.
README for insights
• Confirms use of Python ≥3.10, Poetry for dependency management.
• Instructs placement of ONNX model files in models/ and how to run locally or via Docker Compose.
Main components
a. Client Layer
• CLI client (cli.py)
• HTTP clients (curl, Postman, other services calling the FastAPI endpoint)
b. API Layer (FastAPI)
• main.py – entrypoint, argument parsing, mounting routes
• schemas/embed.py – request/response validation
c. Preprocessing Layer
• utils/preprocess/text.py and html.py – prepare raw input
d. Embedding Layer (Strategy Pattern)
• utils/embed/base.py – abstract interface
• utils/embed/onnx/{cpu.py, cuda.py} – ONNX Runtime implementations
• utils/embed/llama_cpp/embedder.py & session.py – llama-cpp implementation
e. Model Store
• models/ – ONNX model files on disk
f. Infrastructure & Cross-Cutting
• utils/logger.py – logging
• utils/mixins/singleton.py – session or resource pooling
• Docker (Dockerfile + docker-compose)
• GitHub Actions workflow (.github/workflows/llama-cpp.yaml)
Relationships and data flows
1. Client → FastAPI HTTP POST /embed (or CLI)
2. API Layer validates via Pydantic schemas
3. Raw text → Preprocessor → cleaned text
4. Cleaned text → Embedding Layer
– Strategy chooses ONNX or llama-cpp based on config
– Embedding Layer loads model from models/ and runs inference
5. Embedding vector returned to API Layer
6. API Layer serializes response → Client
Key architectural patterns & principles
• Strategy Pattern for pluggable embedders (base.py + onnx vs llama-cpp)
• Singleton or session pooling for ONNX or llama-cpp sessions
• Clear separation of concerns: API, preprocessing, embedding, logging
• Containerization for environment consistency and scaling