Spaces:
Sleeping
Sleeping
Download rag.py from Fsubhan786/AIEngineer: direct link, hf CLI and curl.
- Browser
- Download file 2.55 kB
-
https://huggingface.co/spaces/Fsubhan786/AIEngineer/resolve/main/rag.py
- Command line
-
hf download hf://spaces/Fsubhan786/AIEngineer/rag.py
-
curl -L -o rag.py https://huggingface.co/spaces/Fsubhan786/AIEngineer/resolve/main/rag.py
2.55 kB
| """ | |
| rag.py — Phase 2 retrieval + grounded generation. | |
| Retrieves top-k chunks from Chroma and asks Gemini to answer ONLY from them, | |
| with citations and an explicit refusal when the answer is not in context. | |
| """ | |
| import os | |
| import chromadb | |
| from chromadb.utils import embedding_functions | |
| from google import genai | |
| from google.genai import types | |
| from dotenv import find_dotenv, load_dotenv | |
| load_dotenv(find_dotenv()) | |
| STORE_PATH = "./store" | |
| COLLECTION = "knowledge_base" | |
| EMBED_MODEL = "all-MiniLM-L6-v2" | |
| GEN_MODEL = os.environ.get("GEMINI_MODEL", "gemini-2.5-flash") | |
| SYSTEM = ( | |
| "You answer strictly from the provided context. " | |
| "Cite the source of each claim using its [source#chunk] tag. " | |
| "If the answer is not contained in the context, reply exactly: " | |
| "\"I don't know based on the provided documents.\" " | |
| "Never use outside knowledge." | |
| ) | |
| def _client(): | |
| api_key = os.environ.get("GEMINI_API_KEY") | |
| if not api_key or api_key == "your_gemini_api_key_here": | |
| raise RuntimeError("Set GEMINI_API_KEY in the repository .env file first.") | |
| return genai.Client(api_key=api_key) | |
| def _collection(): | |
| client = chromadb.PersistentClient(path=STORE_PATH) | |
| ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name=EMBED_MODEL) | |
| return client.get_collection(COLLECTION, embedding_function=ef) | |
| def retrieve(question, k=4): | |
| """Return a list of (text, source_tag) for the top-k chunks.""" | |
| col = _collection() | |
| hits = col.query(query_texts=[question], n_results=k) | |
| out = [] | |
| for doc, meta in zip(hits["documents"][0], hits["metadatas"][0]): | |
| tag = f"{meta['source']}#{meta['chunk']}" | |
| out.append((doc, tag)) | |
| return out | |
| def answer(question, k=4, temperature=0.2): | |
| """Grounded answer + the citations used.""" | |
| chunks = retrieve(question, k=k) | |
| if not chunks: | |
| return "I don't know based on the provided documents.", [] | |
| context = "\n\n".join(f"[{tag}]\n{text}" for text, tag in chunks) | |
| prompt = f"Context:\n{context}\n\nQuestion: {question}" | |
| client = _client() | |
| resp = client.models.generate_content( | |
| model=GEN_MODEL, | |
| contents=prompt, | |
| config=types.GenerateContentConfig( | |
| system_instruction=SYSTEM, | |
| temperature=temperature, | |
| ), | |
| ) | |
| citations = [tag for _, tag in chunks] | |
| return resp.text, citations | |
| if __name__ == "__main__": | |
| q = "What is this document about?" | |
| a, cites = answer(q) | |
| print("Q:", q) | |
| print("A:", a) | |
| print("Sources:", ", ".join(cites)) | |