Update pergunte_2.py
Browse files249 unmodified lines250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283249 unmodified linesreturn ["calc", "summary", "full"] if _calc_intent(q) else ["summary", "full"]def retrieve_with_local_filter(question: str, fonte: str, tipo: str, k: int):vectordb = load_vectordb()tiers = _order_tiers_for(question)results: List[Document] = []seen = set()def add_unique(docs: List[Document]):for d in docs:key = (d.page_content, tuple(sorted((d.metadata or {}).items())))if key not in seen:seen.add(key)results.append(d)# ondas por tier (k_expand moderado para não superpescar)for tier in tiers:if len(results) >= k:breakwave_k = max(8, int(k * 2))hits = vectordb.similarity_search(query=question, k=wave_k,filter={"tier": tier} if tier else None)filtered = [d for d in hits if matches_source(d.metadata, fonte) and matches_tipo(d.metadata, tipo)]add_unique(filtered)# fallback (sem tier) se ainda não atingiu kif len(results) < k:wave_k = max(8, int(k * 2))hits = vectordb.similarity_search(question, k=wave_k)filtered = [d for d in hits if matches_source(d.metadata, fonte) and matches_tipo(d.metadata, tipo)]add_unique(filtered)249 unmodified lines250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286249 unmodified linesreturn ["calc", "summary", "full"] if _calc_intent(q) else ["summary", "full"]def retrieve_with_local_filter(question: str, fonte: str, tipo: str, k: int):vdb = load_vectordb()results: List[Document] = []seen = set()def add_unique(docs: List[Document], limit=None):for d in docs:key = (d.page_content, tuple(sorted((d.metadata or {}).items())))if key not in seen:seen.add(key)results.append(d)if limit and len([r for r in results if (r.metadata or {}).get("tier") == "summary"]) >= limit:break# 1) Se NÃO for cálculo, puxe summary primeiro com “cota” de 2if not _calc_intent(question):hits_sum = vdb.similarity_search(question, k=max(8, 2*k), filter={"tier":"summary"})filtered_sum = [d for d in hits_sum if matches_source(d.metadata, fonte) and matches_tipo(d.metadata, tipo)]add_unique(filtered_sum, limit=2)# 2) Depois complete com tiers padrão (summary→full ou calc→summary→full)tiers = _order_tiers_for(question)for tier in tiers:if len(results) >= k:breakhits = vdb.similarity_search(question, k=max(8, 2*k), filter={"tier":tier})filtered = [d for d in hits if matches_source(d.metadata, fonte) and matches_tipo(d.metadata, tipo)]add_unique(filtered)# 3) Fallback sem filtro de tierif len(results) < k:hits = vdb.similarity_search(question, k=max(8, 2*k))filtered = [d for d in hits if matches_source(d.metadata, fonte) and matches_tipo(d.metadata, tipo)]add_unique(filtered)
pergunte_2.py+15-12