File size: 10,431 Bytes
b2b6341 | 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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | """
backend/rag/agent_workflow.py
4-Stage Agentic RAG Workflow
============================
Stage 1 β Planner : Expands 1 question into 3-4 targeted search queries
Stage 2 β Searcher : Runs each query against FAISS, merges + deduplicates chunks
Stage 3 β Validator : Scores & filters chunks, keeps only the most relevant ones
Stage 4 β Synthesizer: Handled by existing generate_answer_stream (no extra call)
Rate-limit strategy:
- Stages 1 & 3 use llama-3.1-8b-instant (FREE tier, 6000 TPM, super fast)
- Stage 4 (synthesis) uses llama-3.3-70b-versatile (main model, existing limit)
- Total extra tokens per query: ~400 (planner) + ~300 (validator) = ~700 tokens
- This is well within free Groq limits (~6000 tokens/min on 8b model)
"""
from __future__ import annotations
import json
import re
import time
from typing import Generator
from groq import Groq
from backend.config import GROQ_API_KEY, GROQ_MODEL
from backend.rag.multi_retriever import MultiSourceResult, _build_source_groups
from backend.rag.retriever import RetrievedChunk
# ββ Small fast model for planner & validator (higher rate limits, cheaper) ββββββ
_FAST_MODEL = "llama-3.1-8b-instant"
# ββ Max chunks to keep after validation βββββββββββββββββββββββββββββββββββββββββ
# Reduced from 12 to 8 to increase context density and reduce "lost in the middle"
_MAX_FINAL_CHUNKS = 8
def _get_groq(api_key: str) -> Groq:
return Groq(api_key=api_key)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# STAGE 1 β PLANNER
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _stage1_planner(question: str, is_legal: bool) -> list[str]:
"""
Uses a few-shot approach to generate 3 targeted queries.
"""
if is_legal:
domain_examples = (
"Example 1: 'Does the IT Act 2000 apply to crypto?' -> ['Section 66 IT Act crypto', 'Indian crypto legality IPC', 'RBI digital asset circulars']\n"
"Example 2: 'Bail for non-bailable offense' -> ['Section 437 CrPC conditions', 'Supreme Court bail guidelines', 'Anticipatory bail landmark cases']"
)
system_prompt = (
"You are a Senior Legal Research Planner. Decompose the user question into 3 precise legal search queries. "
"Focus on: Statutory sections, Case Law, and Procedural guidelines.\n"
f"{domain_examples}\n"
"Return ONLY a JSON array of 3 strings."
)
else:
domain_examples = (
"Example 1: 'How does BERT work?' -> ['BERT architecture transformer', 'Self-attention mechanism BERT', 'BERT pre-training MLM NSP']\n"
"Example 2: 'Climate change impact on farming' -> ['Climate change crop yield statistics', 'Sustainable farming adaptations', 'Soil degradation carbon cycles']"
)
system_prompt = (
"You are an expert Research Planner. Decompose the user question into 3 targeted search queries. "
"Focus on: Technical foundations, Methodology, and Current Benchmarks.\n"
f"{domain_examples}\n"
"Return ONLY a JSON array of 3 strings."
)
prompt = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Question: {question}"},
]
try:
client = _get_groq(GROQ_API_KEY)
resp = client.chat.completions.create(
model=_FAST_MODEL,
messages=prompt,
temperature=0.1, # Lower for consistency
max_tokens=250,
)
raw = resp.choices[0].message.content.strip()
match = re.search(r"\[.*\]", raw, re.DOTALL)
if match:
queries = json.loads(match.group())
if isinstance(queries, list):
# We always prioritize the original question
all_queries = [question] + [str(q) for q in queries[:3]]
return list(dict.fromkeys(all_queries))[:4]
except Exception as e:
print(f"[AgentWorkflow] Planner error: {e}")
return [question]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# STAGE 2 β SEARCHER
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _stage2_searcher(
queries: list[str],
retriever_fn,
source_ids: list[str] | None,
) -> list[RetrievedChunk]:
seen_ids: set[str] = set()
all_chunks: list[RetrievedChunk] = []
for i, q in enumerate(queries):
try:
result: MultiSourceResult = retriever_fn(q, source_ids)
for chunk in result.all_chunks:
if chunk.chunk_id not in seen_ids:
seen_ids.add(chunk.chunk_id)
# We slightly boost the original question's chunks
if i == 0:
chunk.score *= 1.1
all_chunks.append(chunk)
except Exception:
pass
time.sleep(0.02)
return all_chunks
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# STAGE 3 β VALIDATOR (HYBRID)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _stage3_validator(
question: str,
chunks: list[RetrievedChunk],
max_chunks: int = _MAX_FINAL_CHUNKS,
) -> list[RetrievedChunk]:
"""
Combines LLM relevance scoring with Vector similarity (Hybrid).
"""
if not chunks: return []
if len(chunks) <= 3: return chunks # Too few to filter
# Limit chunks to validate to avoid token limits (top 15 by vector score)
candidate_chunks = sorted(chunks, key=lambda c: c.score, reverse=True)[:15]
snippets = "\n".join(
f"ID {i}: {c.chunk_text[:350].strip()}"
for i, c in enumerate(candidate_chunks)
)
prompt = [
{
"role": "system",
"content": (
"You are an Elite Document Validator. Rate the relevance of each document snippet to the question. "
"Return a JSON object where keys are IDs and values are integer scores from 0 (useless) to 10 (perfect answer).\n"
"Example: {'0': 9, '1': 2, '2': 7}"
),
},
{
"role": "user",
"content": f"Question: {question}\n\nSnippets:\n{snippets}",
},
]
try:
client = _get_groq(GROQ_API_KEY)
resp = client.chat.completions.create(
model=_FAST_MODEL,
messages=prompt,
temperature=0.0,
max_tokens=200,
response_format={"type": "json_object"}
)
llm_scores = json.loads(resp.choices[0].message.content)
# Apply Hybrid Scoring: 70% LLM + 30% FAISS
for i, chunk in enumerate(candidate_chunks):
llm_val = float(llm_scores.get(str(i), llm_scores.get(i, 5)))
# Normalize vector score (usually -10 to 10 or 0 to 1)
# We assume a base score of 5 if LLM fails
chunk.score = (llm_val * 1.5) + (chunk.score * 0.5)
# Sort by hybrid score and take top N
final = sorted(candidate_chunks, key=lambda c: c.score, reverse=True)[:max_chunks]
return final
except Exception as e:
print(f"[AgentWorkflow] Validator error: {e}")
return sorted(chunks, key=lambda c: c.score, reverse=True)[:max_chunks]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# MAIN ENTRY POINT
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_agentic_workflow(
question: str,
retriever_fn,
source_ids: list[str] | None = None,
is_legal: bool = False,
) -> tuple[MultiSourceResult, list[str]]:
status_log: list[str] = []
# Planner
status_log.append("π§ Planner: Thinking across multiple research dimensions...")
queries = _stage1_planner(question, is_legal)
status_log.append(f"π― Planner: Targeting {len(queries)} specific data angles")
time.sleep(1)
# Searcher
status_log.append("π Searcher: Parallel retrieval in progress...")
all_chunks = _stage2_searcher(queries, retriever_fn, source_ids)
status_log.append(f"π Searcher: Found {len(all_chunks)} potential evidence blocks")
time.sleep(1)
# Validator
status_log.append("βοΈ Validator: Hybrid re-ranking for maximum precision...")
validated_chunks = _stage3_validator(question, all_chunks)
# Calculate a simple "Confidence" based on top chunk score
confidence = "High" if len(validated_chunks) > 0 and validated_chunks[0].score > 12 else "Medium"
status_log.append(f"β¨ Validator: {confidence} confidence context finalized ({len(validated_chunks)} blocks)")
source_groups = _build_source_groups(validated_chunks)
result = MultiSourceResult(
query_intent="synthesis",
source_groups=source_groups,
all_chunks=validated_chunks,
source_count=len(source_groups),
)
status_log.append("ποΈ Synthesizer: Drafting Professional Research Memorandum...")
return result, status_log
|