Download app/agent/nodes.py from Stoic-2910/acpc-testing-third: direct link, hf CLI and curl.
- Browser
- Download file 5.01 kB
-
https://huggingface.co/spaces/Stoic-2910/acpc-testing-third/resolve/main/app/agent/nodes.py
- Command line
-
hf download hf://spaces/Stoic-2910/acpc-testing-third/app/agent/nodes.py
-
curl -L -o nodes.py https://huggingface.co/spaces/Stoic-2910/acpc-testing-third/resolve/main/app/agent/nodes.py
5.01 kB
| """ | |
| LangGraph node functions for the Agentic RAG pipeline. | |
| Each node receives AgentState and returns a partial state update. | |
| Guardrail logic (intent classification, relevance grading, hallucination checking) | |
| lives in app/guardrails/ β nodes here are thin wrappers that call those modules. | |
| """ | |
| import logging | |
| from langchain_core.messages import HumanMessage, AIMessage, SystemMessage | |
| from app.agent.state import AgentState | |
| from app.agent.prompts import ( | |
| SYSTEM_PROMPT, | |
| GENERATION_PROMPT, | |
| ) | |
| from app.guardrails import classify_query | |
| from app.utils.llm_helpers import get_llm | |
| from app.retrieval.retriever import retrieve_and_rerank, format_sources | |
| from app.config import settings | |
| logger = logging.getLogger(__name__) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Guardrail wrapper nodes | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def classify_intent(state: AgentState) -> dict: | |
| """Node: Classify whether the query is ACPC-related, off-topic, or injection. | |
| Delegates to app.guardrails.intent_classifier. | |
| Only ACPC_RELATED queries proceed; everything else β fallback. | |
| """ | |
| query = state.get("query", "").strip() | |
| result = await classify_query(query) | |
| logger.info( | |
| "classify_intent: classification=%s, route=%s, blocked=%s", | |
| result["classification"], result["route"], result["blocked_reason"], | |
| ) | |
| return {"route": result["route"]} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Core pipeline nodes | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def retrieve(state: AgentState) -> dict: | |
| """Node: Retrieve documents from Qdrant using hybrid search + Cohere rerank.""" | |
| query = state["query"] | |
| logger.info("Retrieving documents for query: %s", query[:80]) | |
| documents = await retrieve_and_rerank(query) | |
| logger.info("Retrieved %d documents", len(documents)) | |
| return {"retrieved_documents": documents} | |
| async def generate(state: AgentState) -> dict: | |
| """Node: Generate an answer from relevant documents.""" | |
| query = state["query"] | |
| relevant_docs = state.get("retrieved_documents", []) | |
| history = state.get("messages", []) | |
| # Build context string from relevant documents | |
| context_parts = [] | |
| for i, doc in enumerate(relevant_docs): | |
| meta = doc.metadata or {} | |
| url = meta.get("url", "") | |
| source_line = f"[Source {i+1}: {meta.get('file_name', 'unknown')}]" | |
| if url: | |
| source_line += f" {url}" | |
| context_parts.append(f"{source_line}\n{doc.page_content}") | |
| context = "\n\n---\n\n".join(context_parts) | |
| generation_content = GENERATION_PROMPT.format(context=context, question=query) | |
| # Build messages: system + trimmed history + current generation prompt | |
| messages = [SystemMessage(content=SYSTEM_PROMPT)] | |
| for msg in history[:-1]: # Skip last (current user message) | |
| messages.append(msg) | |
| messages.append(HumanMessage(content=generation_content)) | |
| llm = get_llm(temperature=0.2) | |
| response = await llm.ainvoke(messages) | |
| generation = response.content.strip() | |
| sources = format_sources(relevant_docs) | |
| logger.info("Generation complete (%d chars, %d sources)", len(generation), len(sources)) | |
| return {"generation": generation, "sources": sources} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Terminal nodes | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def fallback(state: AgentState) -> dict: | |
| """Node: Return the hardcoded fallback response (never LLM-generated).""" | |
| return { | |
| "generation": settings.fallback_response, | |
| "sources": [], | |
| "confidence": 0.0, | |
| } | |
| def respond(state: AgentState) -> dict: | |
| """Terminal node: Package the final response into messages.""" | |
| generation = state.get("generation", settings.fallback_response) | |
| return {"messages": [AIMessage(content=generation)]} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Edge condition functions (routing) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def route_after_classify(state: AgentState) -> str: | |
| """Route after intent classification: retrieve or fallback.""" | |
| route = state.get("route", "fallback") | |
| # Default-deny: only explicit "retrieve" passes | |
| return route if route == "retrieve" else "fallback" | |