Upload 116 files
Browse files- app/agent/nodes.py +6 -6
- app/guardrails/intent_classifier.py +2 -2
- app/retrieval/reranker.py +5 -2
- app/retrieval/retriever.py +16 -3
app/agent/nodes.py
CHANGED
|
@@ -26,14 +26,14 @@ logger = logging.getLogger(__name__)
|
|
| 26 |
# Guardrail wrapper nodes
|
| 27 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
|
| 29 |
-
def classify_intent(state: AgentState) -> dict:
|
| 30 |
"""Node: Classify whether the query is ACPC-related, off-topic, or injection.
|
| 31 |
|
| 32 |
Delegates to app.guardrails.intent_classifier.
|
| 33 |
Only ACPC_RELATED queries proceed; everything else β fallback.
|
| 34 |
"""
|
| 35 |
query = state.get("query", "").strip()
|
| 36 |
-
result = classify_query(query)
|
| 37 |
logger.info(
|
| 38 |
"classify_intent: classification=%s, route=%s, blocked=%s",
|
| 39 |
result["classification"], result["route"], result["blocked_reason"],
|
|
@@ -46,16 +46,16 @@ def classify_intent(state: AgentState) -> dict:
|
|
| 46 |
# Core pipeline nodes
|
| 47 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
|
| 49 |
-
def retrieve(state: AgentState) -> dict:
|
| 50 |
"""Node: Retrieve documents from Qdrant using hybrid search + Cohere rerank."""
|
| 51 |
query = state["query"]
|
| 52 |
logger.info("Retrieving documents for query: %s", query[:80])
|
| 53 |
|
| 54 |
-
documents = retrieve_and_rerank(query)
|
| 55 |
logger.info("Retrieved %d documents", len(documents))
|
| 56 |
return {"retrieved_documents": documents}
|
| 57 |
|
| 58 |
-
def generate(state: AgentState) -> dict:
|
| 59 |
"""Node: Generate an answer from relevant documents."""
|
| 60 |
query = state["query"]
|
| 61 |
relevant_docs = state.get("retrieved_documents", [])
|
|
@@ -81,7 +81,7 @@ def generate(state: AgentState) -> dict:
|
|
| 81 |
messages.append(HumanMessage(content=generation_content))
|
| 82 |
|
| 83 |
llm = get_llm(temperature=0.2)
|
| 84 |
-
response = llm.
|
| 85 |
generation = response.content.strip()
|
| 86 |
|
| 87 |
sources = format_sources(relevant_docs)
|
|
|
|
| 26 |
# Guardrail wrapper nodes
|
| 27 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
|
| 29 |
+
async def classify_intent(state: AgentState) -> dict:
|
| 30 |
"""Node: Classify whether the query is ACPC-related, off-topic, or injection.
|
| 31 |
|
| 32 |
Delegates to app.guardrails.intent_classifier.
|
| 33 |
Only ACPC_RELATED queries proceed; everything else β fallback.
|
| 34 |
"""
|
| 35 |
query = state.get("query", "").strip()
|
| 36 |
+
result = await classify_query(query)
|
| 37 |
logger.info(
|
| 38 |
"classify_intent: classification=%s, route=%s, blocked=%s",
|
| 39 |
result["classification"], result["route"], result["blocked_reason"],
|
|
|
|
| 46 |
# Core pipeline nodes
|
| 47 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
|
| 49 |
+
async def retrieve(state: AgentState) -> dict:
|
| 50 |
"""Node: Retrieve documents from Qdrant using hybrid search + Cohere rerank."""
|
| 51 |
query = state["query"]
|
| 52 |
logger.info("Retrieving documents for query: %s", query[:80])
|
| 53 |
|
| 54 |
+
documents = await retrieve_and_rerank(query)
|
| 55 |
logger.info("Retrieved %d documents", len(documents))
|
| 56 |
return {"retrieved_documents": documents}
|
| 57 |
|
| 58 |
+
async def generate(state: AgentState) -> dict:
|
| 59 |
"""Node: Generate an answer from relevant documents."""
|
| 60 |
query = state["query"]
|
| 61 |
relevant_docs = state.get("retrieved_documents", [])
|
|
|
|
| 81 |
messages.append(HumanMessage(content=generation_content))
|
| 82 |
|
| 83 |
llm = get_llm(temperature=0.2)
|
| 84 |
+
response = await llm.ainvoke(messages)
|
| 85 |
generation = response.content.strip()
|
| 86 |
|
| 87 |
sources = format_sources(relevant_docs)
|
app/guardrails/intent_classifier.py
CHANGED
|
@@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)
|
|
| 20 |
VALID_LABELS = ("ACPC_RELATED", "GREETINGS / SMALL TALK", "OFF_TOPIC", "INJECTION")
|
| 21 |
|
| 22 |
|
| 23 |
-
def classify_query(query: str) -> dict:
|
| 24 |
"""Classify a user query using LLM-based intent detection.
|
| 25 |
|
| 26 |
Returns:
|
|
@@ -41,7 +41,7 @@ def classify_query(query: str) -> dict:
|
|
| 41 |
prompt = INTENT_CLASSIFICATION_PROMPT.format(query=query)
|
| 42 |
|
| 43 |
try:
|
| 44 |
-
response = llm.
|
| 45 |
classification = response.content.strip().upper()
|
| 46 |
except Exception as e:
|
| 47 |
logger.error("LLM error in classify_query: %s β defaulting to fallback", e)
|
|
|
|
| 20 |
VALID_LABELS = ("ACPC_RELATED", "GREETINGS / SMALL TALK", "OFF_TOPIC", "INJECTION")
|
| 21 |
|
| 22 |
|
| 23 |
+
async def classify_query(query: str) -> dict:
|
| 24 |
"""Classify a user query using LLM-based intent detection.
|
| 25 |
|
| 26 |
Returns:
|
|
|
|
| 41 |
prompt = INTENT_CLASSIFICATION_PROMPT.format(query=query)
|
| 42 |
|
| 43 |
try:
|
| 44 |
+
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
| 45 |
classification = response.content.strip().upper()
|
| 46 |
except Exception as e:
|
| 47 |
logger.error("LLM error in classify_query: %s β defaulting to fallback", e)
|
app/retrieval/reranker.py
CHANGED
|
@@ -11,7 +11,7 @@ def get_reranker() -> CohereRerank:
|
|
| 11 |
)
|
| 12 |
|
| 13 |
|
| 14 |
-
def rerank_documents(query: str, documents: list[Document]) -> list[Document]:
|
| 15 |
"""Rerank retrieved documents using Cohere reranker."""
|
| 16 |
if not documents:
|
| 17 |
return []
|
|
@@ -26,4 +26,7 @@ def rerank_documents(query: str, documents: list[Document]) -> list[Document]:
|
|
| 26 |
return []
|
| 27 |
|
| 28 |
reranker = get_reranker()
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
)
|
| 12 |
|
| 13 |
|
| 14 |
+
async def rerank_documents(query: str, documents: list[Document]) -> list[Document]:
|
| 15 |
"""Rerank retrieved documents using Cohere reranker."""
|
| 16 |
if not documents:
|
| 17 |
return []
|
|
|
|
| 26 |
return []
|
| 27 |
|
| 28 |
reranker = get_reranker()
|
| 29 |
+
# Deduplicate documents before reranking if needed
|
| 30 |
+
# (MultiQueryRetriever can sometimes return duplicates)
|
| 31 |
+
|
| 32 |
+
return await reranker.acompress_documents(documents=valid_docs, query=query)
|
app/retrieval/retriever.py
CHANGED
|
@@ -28,7 +28,7 @@ def ensure_pdf_url(url: str) -> str:
|
|
| 28 |
return f"{base_url}.pdf{suffix}"
|
| 29 |
|
| 30 |
|
| 31 |
-
def retrieve_and_rerank(query: str) -> list[Document]:
|
| 32 |
"""
|
| 33 |
Retrieve documents using LangChain Classic's MultiQueryRetriever, and rerank them, returning the top 5.
|
| 34 |
"""
|
|
@@ -46,7 +46,8 @@ def retrieve_and_rerank(query: str) -> list[Document]:
|
|
| 46 |
llm=get_llm(temperature=0.0, model=settings.query_gen_model)
|
| 47 |
)
|
| 48 |
|
| 49 |
-
|
|
|
|
| 50 |
logger.info("Retrieved %d documents via MultiQueryRetriever", len(documents))
|
| 51 |
|
| 52 |
# Unpack LlamaIndex `_node_content` JSON if necessary
|
|
@@ -63,7 +64,19 @@ def retrieve_and_rerank(query: str) -> list[Document]:
|
|
| 63 |
|
| 64 |
# Rerank documents using Cohere
|
| 65 |
if documents:
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
logger.info("Reranked to %d documents via Cohere", len(documents))
|
| 68 |
|
| 69 |
# Return only the top 5
|
|
|
|
| 28 |
return f"{base_url}.pdf{suffix}"
|
| 29 |
|
| 30 |
|
| 31 |
+
async def retrieve_and_rerank(query: str) -> list[Document]:
|
| 32 |
"""
|
| 33 |
Retrieve documents using LangChain Classic's MultiQueryRetriever, and rerank them, returning the top 5.
|
| 34 |
"""
|
|
|
|
| 46 |
llm=get_llm(temperature=0.0, model=settings.query_gen_model)
|
| 47 |
)
|
| 48 |
|
| 49 |
+
# Properly await the async call
|
| 50 |
+
documents = await retriever.ainvoke(query)
|
| 51 |
logger.info("Retrieved %d documents via MultiQueryRetriever", len(documents))
|
| 52 |
|
| 53 |
# Unpack LlamaIndex `_node_content` JSON if necessary
|
|
|
|
| 64 |
|
| 65 |
# Rerank documents using Cohere
|
| 66 |
if documents:
|
| 67 |
+
# deduplicate by content to reduce cost and latency for reranker
|
| 68 |
+
seen = set()
|
| 69 |
+
unique_docs = []
|
| 70 |
+
for d in documents:
|
| 71 |
+
if d.page_content not in seen:
|
| 72 |
+
unique_docs.append(d)
|
| 73 |
+
seen.add(d.page_content)
|
| 74 |
+
|
| 75 |
+
# If we have too many docs, pre-filter to top N before reranking to save time
|
| 76 |
+
if len(unique_docs) > 25:
|
| 77 |
+
unique_docs = unique_docs[:25]
|
| 78 |
+
|
| 79 |
+
documents = await rerank_documents(query=query, documents=unique_docs)
|
| 80 |
logger.info("Reranked to %d documents via Cohere", len(documents))
|
| 81 |
|
| 82 |
# Return only the top 5
|