from openai import OpenAI
from fastembed import SparseTextEmbedding
from qdrant_client import QdrantClient, models
oa = OpenAI()
bm25 = SparseTextEmbedding("Qdrant/bm25")
qdrant = QdrantClient(url="http://localhost:6333")
def answer(question: str, tenant: str) -> str:
dense = oa.embeddings.create(model="text-embedding-3-small", input=question).data[0].embedding
sp = next(bm25.query_embed(question))
only_tenant = models.Filter(must=[models.FieldCondition(key="tenant", match=models.MatchValue(value=tenant))])
hits = qdrant.query_points(
collection_name="docs",
prefetch=[
models.Prefetch(query=dense, using="dense", limit=50, filter=only_tenant),
models.Prefetch(query=models.SparseVector(indices=sp.indices.tolist(), values=sp.values.tolist()), using="sparse", limit=50, filter=only_tenant),
],
query=models.FusionQuery(fusion=models.Fusion.RRF),
limit=8,
).points
context = "\n\n".join(f"[{i}] {h.payload['text']} (source: {h.payload['url']})" for i, h in enumerate(hits, 1))
prompt = f"Answer only from the sources below and cite them as [n]. If they do not answer the question, say so.\n\n{context}\n\nQuestion: {question}"
return oa.responses.create(model="gpt-4.1-mini", input=prompt).output_text