Spaces:
Sleeping

File size: 2,549 Bytes
1a2633a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""
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))