Text Generation
Transformers
edge-impulse
rag
retrieval-augmented-generation
faiss
qwen
documentation
tinyml
edge-ai
Run this model with HF Jobs
Run edgeimpulse/edgeimpulse-docs-rag on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/edgeimpulse/edgeimpulse-docs-rag. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/edgeimpulse/edgeimpulse-docs-rag on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/edgeimpulse/edgeimpulse-docs-rag. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/edgeimpulse/edgeimpulse-docs-rag. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use edgeimpulse/edgeimpulse-docs-rag with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use edgeimpulse/edgeimpulse-docs-rag with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="edgeimpulse/edgeimpulse-docs-rag")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("edgeimpulse/edgeimpulse-docs-rag", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use edgeimpulse/edgeimpulse-docs-rag with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "edgeimpulse/edgeimpulse-docs-rag" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "edgeimpulse/edgeimpulse-docs-rag", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/edgeimpulse/edgeimpulse-docs-rag
- SGLang
How to use edgeimpulse/edgeimpulse-docs-rag with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "edgeimpulse/edgeimpulse-docs-rag" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "edgeimpulse/edgeimpulse-docs-rag", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "edgeimpulse/edgeimpulse-docs-rag" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "edgeimpulse/edgeimpulse-docs-rag", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use edgeimpulse/edgeimpulse-docs-rag with Docker Model Runner:
docker model run hf.co/edgeimpulse/edgeimpulse-docs-rag
Add full Edge Impulse docs RAG assistant (prebuilt index + inference)
Browse filesFiles changed (8)
- .gitattributes+1-34
- README.mdAdded+130
- data/index/chunks.pklAdded+3
- data/index/edge_impulse_docs.faissAdded+3
- data/index/metadata.jsonAdded+8
- rag.pyAdded+154
- requirements.txtAdded+5
- serve.pyAdded+61
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12*.faiss filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130---license: apache-2.0base_model: edgeimpulse/edgeimpulse-docs-qwen-0.5bpipeline_tag: text-generationlibrary_name: transformerstags: - edge-impulse - rag - retrieval-augmented-generation - faiss - qwen - documentation - tinyml - edge-ai---
# Edge Impulse Docs — RAG Assistant
A retrieval-augmented assistant for the [Edge Impulse](https://edgeimpulse.com)documentation. It grounds every answer in a prebuilt vector index of the docs andgenerates with the small quantized model[`edgeimpulse/edgeimpulse-docs-qwen-0.5b`](https://huggingface.co/edgeimpulse/edgeimpulse-docs-qwen-0.5b),so it runs comfortably on a laptop.
- **Retrieval:** FAISS (inner-product) over `data/index`, embedded with `sentence-transformers/all-MiniLM-L6-v2` (384-dim, the same model the index was built with).- **Generation:** the 0.5B GGUF, served through any OpenAI-compatible endpoint (llama.cpp `llama-server` or Ollama). No training stack required.- **Grounded + cited:** answers are constrained to the retrieved context and each response lists its source documents.
This repo ships only what you need to **run** the assistant — the prebuilt indexand the inference code. The raw document corpus and the index-building pipelineare not included.
## Contents
| File | Purpose || --- | --- || `data/index/edge_impulse_docs.faiss` | FAISS inner-product index of the docs || `data/index/chunks.pkl` | Chunk text + source metadata (aligned to the index) || `data/index/metadata.json` | Embedding model + index parameters || `rag.py` | Retrieval + grounded generation (CLI + importable) || `serve.py` | Minimal Flask HTTP API (`POST /ask`) || `requirements.txt` | Runtime dependencies |
## Quickstart
**1. Install dependencies and download this repo**
```bashpip install -r requirements.txthf download edgeimpulse/edgeimpulse-docs-rag --local-dir edgeimpulse-docs-ragcd edgeimpulse-docs-rag```
**2. Start the generator** (pick one)
llama.cpp:
```bashhf download edgeimpulse/edgeimpulse-docs-qwen-0.5b qwen-edgeai-q4_k_m.gguf --local-dir .llama-server -m qwen-edgeai-q4_k_m.gguf -c 4096 --port 8080 --jinja```
Ollama:
```bashollama run hf.co/edgeimpulse/edgeimpulse-docs-qwen-0.5b# then point rag.py at Ollama's OpenAI-compatible port:export RAG_API_BASE=http://127.0.0.1:11434/v1export RAG_MODEL=hf.co/edgeimpulse/edgeimpulse-docs-qwen-0.5b```
**3. Ask a question**
```bashpython rag.py "How do I deploy a model to run on a Linux target as an .eim file?"```
Only see what was retrieved (no generation):
```bashpython rag.py "How do I create an API key?" --no-generate```
Serve it over HTTP:
```bashpython serve.py --host 0.0.0.0 --port 8000curl -s localhost:8000/ask -H 'content-type: application/json' \ -d '{"question": "What is the data forwarder?"}'```
## Configuration
`rag.py` reads these environment variables (all optional):
| Variable | Default | Meaning || --- | --- | --- || `RAG_INDEX_DIR` | `data/index` | Location of the FAISS index + chunks || `RAG_API_BASE` | `http://127.0.0.1:8080/v1` | OpenAI-compatible generation endpoint || `RAG_MODEL` | `edgeimpulse/edgeimpulse-docs-qwen-0.5b` | Model name passed to the endpoint |
## How it works
```question ──▶ MiniLM embed ──▶ FAISS top-k ──▶ context + question │ ▼ edgeimpulse-docs-qwen-0.5b (llama.cpp / Ollama) │ ▼ grounded answer + cited sources```
The generator is a small model, so retrieval quality matters: the assistant ismost accurate when the right chunk is retrieved, and it may be terse or repeatitself on out-of-scope questions. Sampling defaults (`temperature 0.3`,`repeat_penalty 1.2`) are tuned to keep it from looping.
## Related
- Generator model: [`edgeimpulse/edgeimpulse-docs-qwen-0.5b`](https://huggingface.co/edgeimpulse/edgeimpulse-docs-qwen-0.5b)- API-scoped variant: [`edgeimpulse/edgeimpulse-api-docs-rag`](https://huggingface.co/edgeimpulse/edgeimpulse-api-docs-rag)
## License
Apache-2.0. Documentation content belongs to Edge Impulse.123version https://git-lfs.github.com/spec/v1oid sha256:a7f90aa5667bc03f9743895628228e5a43d186a17d677dfce039f191c65b68a9size 922471123version https://git-lfs.github.com/spec/v1oid sha256:7a00fcd8072d979872290f1c180c0c603bd6d01bf47fa34db28399f84a35daabsize 83716512345678{
"embedding_model": "sentence-transformers/all-MiniLM-L6-v2",
"docs_dir": "data/raw_docs",
"chunk_count": 545,
"embedding_dim": 384,
"chunk_chars": 1800,
"overlap_chars": 250
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Edge Impulse docs RAG — retrieval + grounded generation.
Retrieval: FAISS (inner-product) over the prebuilt index in ``data/index`` usingthe same ``all-MiniLM-L6-v2`` sentence embedder the index was built with.
Generation: the published quantized model ``edgeimpulse/edgeimpulse-docs-qwen-0.5b``served through any OpenAI-compatible endpoint — e.g. llama.cpp's ``llama-server``or Ollama. Only the tiny GGUF is needed for generation, so no training stack isrequired to run this assistant.
The raw document corpus and the index-building pipeline are intentionally notpart of this repository; the prebuilt index is all you need at inference time."""from __future__ import annotations
import argparseimport jsonimport osimport picklefrom functools import lru_cachefrom pathlib import Pathfrom typing import Any
import faissimport requestsfrom sentence_transformers import SentenceTransformer
DEFAULT_INDEX_DIR = Path(os.environ.get("RAG_INDEX_DIR", "data/index"))
# OpenAI-compatible generation endpoint (llama.cpp `llama-server` or Ollama).# llama.cpp : llama-server -m qwen-edgeai-q4_k_m.gguf --port 8080 --jinja# ollama : ollama run hf.co/edgeimpulse/edgeimpulse-docs-qwen-0.5bDEFAULT_API_BASE = os.environ.get("RAG_API_BASE", "http://127.0.0.1:8080/v1")DEFAULT_MODEL = os.environ.get("RAG_MODEL", "edgeimpulse/edgeimpulse-docs-qwen-0.5b")DEFAULT_API_KEY = os.environ.get("RAG_API_KEY", "sk-no-key-required")
SYSTEM_PROMPT = ( "You are an Edge Impulse documentation assistant. Answer only from the " "provided context. If the context does not contain the answer, say what is " "missing and suggest the closest relevant docs source. Be concise.")
@lru_cache(maxsize=1)def load_retriever(index_dir: str): root = Path(index_dir) metadata = json.loads((root / "metadata.json").read_text(encoding="utf-8")) index = faiss.read_index(str(root / "edge_impulse_docs.faiss")) with (root / "chunks.pkl").open("rb") as f: chunks = pickle.load(f) embedder = SentenceTransformer(metadata["embedding_model"]) return index, chunks, embedder, metadata
def retrieve(question: str, index_dir: Path = DEFAULT_INDEX_DIR, k: int = 4) -> list[dict[str, Any]]: index, chunks, embedder, _ = load_retriever(str(index_dir)) q_emb = embedder.encode( [question], convert_to_numpy=True, normalize_embeddings=True ).astype("float32") scores, ids = index.search(q_emb, k) results: list[dict[str, Any]] = [] for score, idx in zip(scores[0], ids[0]): if idx < 0: continue record = dict(chunks[int(idx)]) record["score"] = float(score) results.append(record) return results
def build_messages(question: str, contexts: list[dict[str, Any]]) -> list[dict[str, str]]: context_text = "\n\n".join( f"Source: {item['source']}\n{item['text']}" for item in contexts ) user = f"Context:\n{context_text}\n\nQuestion: {question}" return [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user}, ]
def generate( messages: list[dict[str, str]], api_base: str = DEFAULT_API_BASE, model: str = DEFAULT_MODEL, api_key: str = DEFAULT_API_KEY, max_new_tokens: int = 320,) -> str: payload = { "model": model, "messages": messages, "temperature": 0.3, "top_p": 0.9, "max_tokens": max_new_tokens, # Honoured by llama.cpp's server; ignored by backends that don't support it. "repeat_penalty": 1.2, } resp = requests.post( f"{api_base.rstrip('/')}/chat/completions", headers={"Authorization": f"Bearer {api_key}"}, json=payload, timeout=120, ) resp.raise_for_status() return resp.json()["choices"][0]["message"]["content"].strip()
def ask( question: str, index_dir: Path = DEFAULT_INDEX_DIR, k: int = 4, max_new_tokens: int = 320, no_generate: bool = False, api_base: str = DEFAULT_API_BASE, model: str = DEFAULT_MODEL,) -> str: contexts = retrieve(question, index_dir, k) sources = "\n".join(f"- {item['source']} ({item['score']:.3f})" for item in contexts) if no_generate: return "Retrieved context:\n" + sources answer = generate( build_messages(question, contexts), api_base=api_base, model=model, max_new_tokens=max_new_tokens, ) return f"{answer}\n\nSources:\n{sources}"
def main() -> None: parser = argparse.ArgumentParser(description="Ask the Edge Impulse docs RAG assistant.") parser.add_argument("question") parser.add_argument("--index-dir", type=Path, default=DEFAULT_INDEX_DIR) parser.add_argument("--k", type=int, default=4) parser.add_argument("--max-new-tokens", type=int, default=320) parser.add_argument("--api-base", default=DEFAULT_API_BASE) parser.add_argument("--model", default=DEFAULT_MODEL) parser.add_argument("--no-generate", action="store_true", help="Only print retrieved chunks.") args = parser.parse_args() print( ask( args.question, index_dir=args.index_dir, k=args.k, max_new_tokens=args.max_new_tokens, no_generate=args.no_generate, api_base=args.api_base, model=args.model, ) )
if __name__ == "__main__": main()12345faiss-cpu>=1.8sentence-transformers>=2.2numpy>=1.24requests>=2.31flask>=3.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Minimal HTTP server for the Edge Impulse docs RAG assistant.
python serve.py --host 0.0.0.0 --port 8000
POST /ask {"question": "...", "k": 4} -> {"answer": "..."}GET /health -> {"ok": true}"""from __future__ import annotations
import argparsefrom pathlib import Path
from flask import Flask, jsonify, request
from rag import DEFAULT_API_BASE, DEFAULT_INDEX_DIR, DEFAULT_MODEL, ask
def create_app(index_dir: Path, api_base: str, model: str, k: int) -> Flask: app = Flask(__name__)
@app.get("/health") def health(): return jsonify({"ok": True})
@app.post("/ask") def ask_route(): payload = request.get_json(silent=True) or {} question = str(payload.get("question", "")).strip() if not question: return jsonify({"error": "question is required"}), 400 try: answer = ask( question, index_dir=index_dir, k=int(payload.get("k", k)), max_new_tokens=int(payload.get("max_new_tokens", 320)), api_base=api_base, model=model, ) return jsonify({"answer": answer}) except Exception as exc: # noqa: BLE001 - surface the error to the client return jsonify({"error": str(exc)}), 500
return app
def main() -> None: parser = argparse.ArgumentParser(description="Serve the Edge Impulse docs RAG assistant.") parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", type=int, default=8000) parser.add_argument("--index-dir", type=Path, default=DEFAULT_INDEX_DIR) parser.add_argument("--api-base", default=DEFAULT_API_BASE) parser.add_argument("--model", default=DEFAULT_MODEL) parser.add_argument("--k", type=int, default=4) args = parser.parse_args() app = create_app(args.index_dir, args.api_base, args.model, args.k) app.run(host=args.host, port=args.port)
if __name__ == "__main__": main().gitattributes+1-34
README.mdAdded+130
data/index/chunks.pklAdded+3
data/index/edge_impulse_docs.faissAdded+3
data/index/metadata.jsonAdded+8
rag.pyAdded+154
requirements.txtAdded+5
serve.pyAdded+61