JanSahayak / src /graph.py
Darshan03's picture
Finalized JanSahayak MAS: Advanced Memory (mem0+Supabase), Guardrails AI, and OTel Observability
a1bdec0
Raw History Blame Contribute Delete
22.2 kB
from typing import Annotated, Literal, Tuple
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
from langchain_core.messages import HumanMessage
from src.state.state import AgentState
import json
from src.agents.base import (
orchestrator_agent, policy_agent, eligibility_agent,
benefit_agent, advocacy_agent
)
from src.tools.tools import (
retrieve_policy, check_eligibility_rules, find_benefits_database,
calculate_structured_eligibility, verify_citizen_document,
scrape_policy_updates, prefill_application_form
)
from src.utils.config import get_zynd_agent
from src.utils.logger import setup_logger
from src.utils.validators import IndianCivicRelevance, GroundingValidator
from src.core.memory import memory_service
from guardrails import Guard
logger = setup_logger("Graph")
# --- Nodes ---
relevance_guard = Guard().use(IndianCivicRelevance())
def orchestrator_node(state: AgentState):
logger.info("Orchestrator processing...")
try:
input_text = (state.get("input_text") or "")
if state.get("messages"):
for msg in reversed(state["messages"]):
if isinstance(msg, HumanMessage):
input_text = msg.content
break
# Guardrail AI: Input Relevance Check
logger.info(f"Guardrail Check: Validating relevance for input: '{input_text[:50]}...'")
result = relevance_guard.validate(input_text)
if not result.validation_passed:
logger.warning(f"Guardrail Fail: {result.error}")
return {"current_intent": "OUT_OF_SCOPE"}
# Check if intent is already set (from UI option selection)
if state.get("current_intent") and state.get("selected_option"):
logger.info(f"Intent already set by UI: {state['current_intent']}")
return {"current_intent": state["current_intent"]}
# ── Long-term Memory Retrieval (mem0 + Supabase) ──
user_id = state.get("user_id", "default_citizen")
long_term_context = memory_service.get_context_string(user_id, input_text)
# ── Short-term Summary (Sliding Window) ──
existing_summary = state.get("summary", "")
language = state.get("language", "en")
# Enrich prompt with retrieved context
enriched_messages = messages
if long_term_context or existing_summary:
context_prompt = "Relevant context from previous interactions:\n"
if existing_summary:
context_prompt += f"Summary of previous turns: {existing_summary}\n"
if long_term_context:
context_prompt += f"Known facts about citizen: {long_term_context}\n"
# Prepend context as a system nudge (or merge into first message)
# For simplicity, we just pass the context to the agent
logger.info(f"Enriching orchestrator with {len(long_term_context)} chars of memory.")
decision = orchestrator_agent.invoke({
"messages": messages,
"language": language,
"context": f"{existing_summary}\n{long_term_context}"
})
# Store the current interaction in long-term memory asynchronously
# (Conceptual: in real app would trigger after response)
# memory_service.add_memory(user_id, input_text)
return {"current_intent": decision.next_agent}
except Exception as e:
logger.error(f"Orchestrator Error: {e}")
return {"current_intent": "__end__"}
def policy_node(state: AgentState):
logger.info("Transferring to Policy Navigator...")
try:
input_text = state.get("input_text", "")
if state.get("messages"):
for msg in reversed(state["messages"]):
if isinstance(msg, HumanMessage):
input_text = msg.content
break
language = state.get("language", "en")
# Invoke Subgraph
result = policy_navigator_graph.invoke({"input_text": input_text, "language": language})
response_text = result.get("final_markdown_response", "No response generated.")
# Extract context from retrieved docs for grounding
docs = result.get("retrieved_docs", [])
context_text = "\n\n".join([d.page_content for d in docs]) if docs else ""
# Guardrail: Grounding Check
is_grounded, correction = validate_grounding(response_text, context_text)
if not is_grounded:
logger.warning(f"Grounding Fail: {correction}. Retrying...")
retry_input = f"{input_text}\n\n[SYSTEM CORRECTION]: Your previous response had issues: {correction}. Please rewrite it accurately."
result = policy_navigator_graph.invoke({"input_text": retry_input, "language": language})
response_text = result.get("final_markdown_response", response_text)
return {"messages": [HumanMessage(content=response_text)]}
except Exception as e:
logger.error(f"Policy Navigator Error: {e}")
return {"messages": [HumanMessage(content="I encountered an error navigating the policy.")]}
from src.agents.eligibility_verification import eligibility_graph
def eligibility_node(state: AgentState):
logger.info("Transferring to Eligibility Agent...")
try:
input_text = state.get("input_text", "")
if state.get("messages"):
for msg in reversed(state["messages"]):
if isinstance(msg, HumanMessage):
input_text = msg.content
break
user_profile = state.get("user_profile")
language = state.get("language", "en")
# Invoke Subgraph
result = eligibility_graph.invoke({
"input_text": input_text,
"citizen_profile": user_profile,
"language": language
})
response_text = result.get("final_markdown_response", "No response generated.")
# Context extraction (simplified for now as eligibility agent uses engine primarily)
# In a real RAG check, we'd include retrieved rules here.
context_text = ""
# Guardrail: Grounding Check
is_grounded, correction = validate_grounding(response_text, context_text)
if not is_grounded:
logger.warning(f"Grounding Fail: {correction}. Retrying...")
retry_input = f"{input_text}\n\n[SYSTEM CORRECTION]: {correction}. Please rewrite purely based on rules."
result = eligibility_graph.invoke({
"input_text": retry_input,
"citizen_profile": user_profile,
"language": language
})
response_text = result.get("final_markdown_response", response_text)
return {"messages": [HumanMessage(content=response_text)]}
except Exception as e:
logger.error(f"Eligibility Agent Error: {e}")
return {"messages": [HumanMessage(content="I encountered an error checking eligibility.")]}
from src.agents.benefits_matching import benefits_graph
def benefit_node(state: AgentState):
logger.info("Transferring to Benefits Agent...")
try:
input_text = state.get("input_text", "")
if state.get("messages"):
for msg in reversed(state["messages"]):
if isinstance(msg, HumanMessage):
input_text = msg.content
break
user_profile = state.get("user_profile")
language = state.get("language", "en")
# Invoke Subgraph
result = benefits_graph.invoke({
"input_text": input_text,
"citizen_profile": user_profile,
"language": language
})
response_text = result.get("final_markdown_response", "No response generated.")
# Context extraction
docs = result.get("retrieved_docs", [])
context_text = "\n\n".join([d.page_content for d in docs]) if docs else ""
# Guardrail: Grounding Check
is_grounded, correction = validate_grounding(response_text, context_text)
if not is_grounded:
logger.warning(f"Grounding Fail: {correction}. Retrying...")
retry_input = f"{input_text}\n\n[SYSTEM CORRECTION]: {correction}. Rewrite using only found benefits."
result = benefits_graph.invoke({
"input_text": retry_input,
"citizen_profile": user_profile,
"language": language
})
response_text = result.get("final_markdown_response", response_text)
return {"messages": [HumanMessage(content=response_text)]}
except Exception as e:
logger.error(f"Benefits Agent Error: {e}")
return {"messages": [HumanMessage(content="I encountered an error finding benefits.")]}
from src.agents.advocacy_agent import advocacy_graph
from src.agents.conversation_agent import conversation_graph, run_conversation
def conversation_node(state: AgentState):
"""Life-first conversational discovery flow"""
logger.info("Transferring to Conversation Agent...")
try:
input_text = state.get("input_text", "")
if state.get("messages"):
for msg in reversed(state["messages"]):
if isinstance(msg, HumanMessage):
input_text = msg.content
break
# Get existing conversation state if available
existing_state = state.get("conversation_state")
# Prepare chat history from messages
messages = state.get("messages", [])
chat_history = []
for msg in messages:
role = "User" if isinstance(msg, HumanMessage) else "Sahayak"
content = msg.content
chat_history.append(f"{role}: {content}")
language = state.get("language", "en")
# Pass chat_history to run_conversation
result = run_conversation(input_text, existing_state, language=language, chat_history=chat_history)
response_text = result.get("final_markdown_response")
if not response_text:
response_text = result.get("current_response", "How can I help you today?")
return {
"messages": [HumanMessage(content=response_text)],
"conversation_state": result
}
except Exception as e:
logger.error(f"Conversation Agent Error: {e}")
return {"messages": [HumanMessage(content="I'm here to help. What kind of support are you looking for?")]}
def advocacy_node(state: AgentState):
logger.info("Transferring to Advocacy Agent...")
try:
input_text = state.get("input_text", "")
if state.get("messages"):
for msg in reversed(state["messages"]):
if isinstance(msg, HumanMessage):
input_text = msg.content
break
# Enrich with user profile if available
user_profile = state.get("user_profile")
if user_profile:
logger.info(f"Advocacy Agent using user profile: {user_profile}")
language = state.get("language", "en")
result = advocacy_graph.invoke({"input_text": input_text, "language": language})
response_text = result.get("final_markdown_response", "No response generated.")
return {"messages": [HumanMessage(content=response_text)]}
except Exception as e:
logger.error(f"Advocacy Agent Error: {e}")
return {"messages": [HumanMessage(content="I encountered an error generating advocacy guidance.")]}
# ── Semantic & Grounding Guardrails ──
grounding_guard = Guard().use(GroundingValidator())
def validate_grounding(response_text: str, context_text: str = None) -> Tuple[bool, str]:
"""
Validates if the agent's response is grounded in the provided context using Guardrails AI.
"""
try:
# Pass context as metadata for the validator
result = grounding_guard.validate(response_text, metadata={"context": context_text})
if not result.validation_passed:
return False, result.error or "Response not supported by retrieved context."
return True, ""
except Exception as e:
logger.error(f"Grounding Guard Error: {e}")
return True, "" # Default to true on error to avoid agent loops
# ── Output Language Guardrail ──
def refiner_node(state: AgentState):
"""
Final node to ensure the response matches the user's selected language
and follows the brand tone.
"""
logger.info("JanSahayak Refiner: Polishing final response...")
last_message = state["messages"][-1].content if state["messages"] else ""
target_language = state.get("language", "en")
if not last_message or last_message.startswith("Validation Error"):
return {}
prompt = f"""
You are the JanSahayak Language Refiner.
Ensure the following response is in '{target_language}'.
If it's already in '{target_language}', polish the tone to be supportive and friendly.
If it's NOT in '{target_language}', translate it completely to '{target_language}'.
RESPONSE:
{last_message}
Output ONLY the polished/translated markdown response.
"""
try:
from src.agents.base import llm
refined = llm.invoke([HumanMessage(content=prompt)])
return {"messages": [HumanMessage(content=refined.content)]}
except Exception as e:
logger.error(f"Refiner Error: {e}")
return {}
# ── Sliding Summary Node ──
def summarize_messages(state: AgentState):
"""
Summarizes the oldest messages if the conversation becomes too long.
This implements the 'Sliding Summary' context management.
"""
messages = state.get("messages", [])
if len(messages) <= 6:
return {}
logger.info(f"Summarizing {len(messages)} messages to maintain context window.")
# Take the oldest 4 messages to summarize
to_summarize = messages[:-2]
history_str = "\n".join([f"{msg.type}: {msg.content}" for msg in to_summarize])
existing_summary = state.get("summary", "")
prompt = f"""
This is a conversation between a citizen and JanSahayak (AI Assistant).
Existing Summary: {existing_summary}
New interactions to incorporate: {history_str}
Provide an updated, concise summary that captures all key citizen details
and task progress. Avoid repetition.
"""
try:
from src.agents.base import llm
updated_summary = llm.invoke([HumanMessage(content=prompt)]).content
# Truncate messages: Keep only the last 2 and the new summary
# In LangGraph, 'operator.add' on messages means we can't easily "remove"
# without custom state logic, but for this implementation we just
# manage the summary and let the UI/Agent use the summary field.
# Also store facts in long-term memory (mem0)
user_id = state.get("user_id", "default_citizen")
memory_service.add_memory(user_id, updated_summary)
return {
"summary": updated_summary,
# Note: We don't delete messages here because 'operator.add'
# would just append them. Real deletion needs a different state reducer.
}
except Exception as e:
logger.error(f"Summary Error: {e}")
return {}
# ── HITL Escalation Node ──
HITL_ESCALATION_KEYWORDS = [
"human", "caseworker", "real person", "talk to someone",
"escalate", "help me more", "not satisfied", "speak to agent"
]
def escalation_node(state: AgentState):
"""Generate a case summary and flag for human handoff."""
logger.info("HITL Escalation triggered β€” generating case summary for human handoff.")
input_text = state.get("input_text", "")
user_profile = state.get("user_profile", {})
escalation_reason = state.get("escalation_reason", "User requested human assistance")
# Collect conversation history
messages = state.get("messages", [])
history_summary = []
for msg in messages[-10:]: # Last 10 messages
role = "Citizen" if isinstance(msg, HumanMessage) else "System"
content = msg.content if hasattr(msg, "content") else str(msg)
history_summary.append(f"[{role}] {content[:200]}")
case_summary = f"""
## Human Escalation Case Summary
**Escalation Reason:** {escalation_reason}
**Language Preference:** {state.get('language', 'en')}
**Current Intent:** {state.get('current_intent', 'Unknown')}
### Citizen Profile
{json.dumps(user_profile, indent=2, default=str) if user_profile else 'No profile collected yet'}
### Original Query
{input_text}
### Conversation History (last 10 messages)
{'\n'.join(history_summary) if history_summary else 'No prior messages'}
### Recommended Actions
- Review citizen's eligibility and documents
- Provide personalized guidance
- Follow up within 48 hours
"""
response_text = (
"I understand this needs more personalized attention. "
"I've prepared a case summary and flagged your request for a human caseworker.\n\n"
"**What happens next:**\n"
"1. A trained caseworker will review your situation\n"
"2. They will contact you within 24-48 hours\n"
"3. In the meantime, you can call the government helpline: **1800-111-555**\n\n"
"> Your case reference has been saved. You don't need to explain everything again."
)
return {
"messages": [HumanMessage(content=response_text)],
"needs_human": True,
"case_summary": case_summary
}
# --- Graph ---
workflow = StateGraph(AgentState)
workflow.add_node("orchestrator", orchestrator_node)
workflow.add_node("conversation_agent", conversation_node)
workflow.add_node("policy_agent", policy_node)
workflow.add_node("eligibility_agent", eligibility_node)
workflow.add_node("benefit_agent", benefit_node)
workflow.add_node("advocacy_agent", advocacy_node)
workflow.add_node("escalation", escalation_node)
workflow.add_node("refiner", refiner_node)
workflow.add_node("summarizer", summarize_messages)
# Tool Node (Shared β€” includes all Phase 2-5 tools)
tools = [
retrieve_policy, check_eligibility_rules, find_benefits_database,
calculate_structured_eligibility, verify_citizen_document,
scrape_policy_updates, prefill_application_form
]
tool_node = ToolNode(tools)
workflow.add_node("tools", tool_node)
# --- Edges ---
def route_orchestrator(state: AgentState) -> Literal["conversation_agent", "policy_agent", "eligibility_agent", "benefit_agent", "advocacy_agent", "escalation", "__end__"]:
# Check for explicit human escalation request
input_text = (state.get("input_text") or "").lower()
if any(kw in input_text for kw in HITL_ESCALATION_KEYWORDS):
return "escalation"
intent = state.get("current_intent")
if intent == "CONVERSATION_DISCOVERY":
return "conversation_agent"
elif intent == "POLICY_INTERPRETER":
return "policy_agent"
elif intent == "ELIGIBILITY_VERIFIER":
return "eligibility_agent"
elif intent == "BENEFIT_MATCHER":
return "benefit_agent"
elif intent == "CITIZEN_ADVOCATE":
return "advocacy_agent"
elif intent == "OUT_OF_SCOPE":
return "conversation_agent"
else:
return "__end__"
workflow.set_entry_point("orchestrator")
workflow.add_conditional_edges("orchestrator", route_orchestrator)
def route_agent_output(state: AgentState) -> Literal["tools", "escalation", "refiner", "__end__"]:
# Check if agent flagged for human escalation
if state.get("needs_human"):
return "escalation"
last_message = state["messages"][-1]
# If the last message is a Tool Call, route to tools
if hasattr(last_message, "tool_calls") and len(last_message.tool_calls) > 0:
return "tools"
# If it's a final response, route through Refiner
return "refiner"
# Connect agents to tools/escalation/refiner and back
for agent_name in ["conversation_agent", "policy_agent", "eligibility_agent", "benefit_agent", "advocacy_agent"]:
workflow.add_conditional_edges(agent_name, route_agent_output)
# Escalation and Refiner go to Summarizer then end
workflow.add_edge("escalation", "summarizer")
workflow.add_edge("refiner", "summarizer")
workflow.add_edge("summarizer", END)
# Tools go back to the agent that called them
# NOTE: This simple graph assumes the last agent called the tool.
# LangGraph ToolNode execution updates state["messages"], so we just need to route back to the active agent.
# But "tools" node output doesn't know who called it.
# We need to use valid routing logic.
# For simplicity, we can route based on `current_intent` preserved in state.
def route_tools_back(state: AgentState):
intent = state.get("current_intent")
if intent == "CONVERSATION_DISCOVERY":
return "conversation_agent"
elif intent == "POLICY_INTERPRETER":
return "policy_agent"
elif intent == "ELIGIBILITY_VERIFIER":
return "eligibility_agent"
elif intent == "BENEFIT_MATCHER":
return "benefit_agent"
elif intent == "CITIZEN_ADVOCATE":
return "advocacy_agent"
return "__end__"
workflow.add_conditional_edges("tools", route_tools_back)
import sqlite3
try:
from langgraph.checkpoint.sqlite import SqliteSaver
# Ensure the database connection is thread-safe for Flask
# check_same_thread=False is needed because Flask uses multiple threads
conn = sqlite3.connect("jan_sahayak.db", check_same_thread=False)
checkpointer = SqliteSaver(conn)
logger.info("Using SqliteSaver for persistent chat history.")
except ImportError:
logger.warning("langgraph-checkpoint-sqlite not found. Falling back to MemorySaver (History will not persist).")
from langgraph.checkpoint.memory import MemorySaver
checkpointer = MemorySaver()
app = workflow.compile(checkpointer=checkpointer)