backend / agent /graph.py
riosiahaan's picture
Debugging graph(2)
fc950e2
Raw History Blame Contribute Delete
11.6 kB
import os
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
from langchain_core.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ToolMessage
import operator
from .tools import tools # full tool list (used by ToolNode; must remain complete)
from .llm import get_llm, invoke_with_fallback
from .intent_classifier import classify_intent, get_tools_for_intent
# Define State
class AgentState(TypedDict):
messages: Annotated[list[BaseMessage], operator.add]
selected_tools: list
is_first_call: bool
# System Prompt
SYSTEM_PROMPT = """Anda adalah asisten AI BPS Kabupaten Flores Timur.
Hanya jawab pertanyaan seputar data statistik dan informasi BPS Kabupaten Flores Timur.
PENGGUNAAN TOOL:
- `rag_tool`: data statistik (populasi, inflasi, dll)
- `search_tool`: info umum BPS Flores Timur (kepala BPS, alamat, berita) β€” HANYA dari web BPS Flores Timur
- `rag_excel_tool`: HANYA jika user minta "download", "export", atau "excel"
JIKA pertanyaan tidak terkait BPS Flores Timur:
"Maaf, saya hanya membantu pertanyaan seputar BPS Kabupaten Flores Timur."
Selalu profesional dan berbasis data."""
from langchain_core.runnables import RunnableConfig
def safe_trim(messages, limit=10):
"""
Smart trimming that preserves the integrity of the conversation for Gemini.
Rules:
1. Always keep SystemMessage.
2. Always end with the most recent messages.
3. Ensure the trimmed history starts with a HumanMessage (User) if possible,
to strictly satisfy "System -> User -> Model" pattern.
4. NEVER cut in the middle of a Tool Call chain (Model -> Tool -> Model).
"""
if not messages:
return messages
system_message = messages[0] if isinstance(messages[0], SystemMessage) else None
# Working with non-system messages
history = messages[1:] if system_message else messages
if len(history) <= limit:
return messages
trimmed = []
# Iterate backwards from the end
i = len(history) - 1
while i >= 0:
msg = history[i]
trimmed.insert(0, msg)
# Stop condition:
# We have at least 'limit' messages AND we just added a HumanMessage.
# This ensures we start a turn cleanly with a User.
if len(trimmed) >= limit and isinstance(msg, HumanMessage):
break
i -= 1
# Safety Check:
# If we exhausted the loop but didn't find a clean HumanMessage start (rare, but possible if massive tool chain),
# we might have a starting message that is AIMessage or ToolMessage.
# While generic AIMessage might be accepted, broken Tool chains are fatal.
#
# IMPORTANT: Only strip from the START of history (old orphan tool messages).
# NEVER strip if it would remove the most recent tool call/result chain,
# because that would cause the LLM to think the tool hasn't run yet β†’ LOOP.
# Find the index of the last HumanMessage to use as a safe guard.
last_human_idx = -1
for idx, m in enumerate(trimmed):
if isinstance(m, HumanMessage):
last_human_idx = idx
while trimmed:
first = trimmed[0]
is_tool_call = isinstance(first, AIMessage) and first.tool_calls
is_tool_result = isinstance(first, ToolMessage)
if (is_tool_call or is_tool_result) and (len(trimmed) > 1) and (trimmed.index(first) < last_human_idx or last_human_idx == -1):
# Only strip orphan tool artifacts that appear BEFORE the last human turn.
trimmed.pop(0)
else:
break
return [system_message] + trimmed if system_message else trimmed
# ---------------------------------------------------------------------------
# History summarization node (item 3 β€” Trim Conversation History)
# ---------------------------------------------------------------------------
# This node runs BEFORE agent_node every cycle. If the non-system history
# exceeds HISTORY_WINDOW messages, it compresses the oldest half into a
# single summary message so the context window stays bounded.
# ---------------------------------------------------------------------------
HISTORY_WINDOW = 10 # keep at most this many recent messages (excl. system)
SUMMARY_TRIGGER = 14 # start summarising once history grows past this
async def history_trim_node(state: AgentState, config):
"""
Compresses old conversation turns into a single summary message when the
history exceeds SUMMARY_TRIGGER messages. Returns the updated message list.
"""
messages = state["messages"]
# Separate system message from the rest
if messages and isinstance(messages[0], SystemMessage):
system_msg = messages[0]
history = messages[1:]
else:
system_msg = None
history = messages
if len(history) <= SUMMARY_TRIGGER:
# Nothing to do β€” history is still within the acceptable window
return {"messages": messages}
# Split: compress everything except the most recent HISTORY_WINDOW messages
to_compress = history[: len(history) - HISTORY_WINDOW]
to_keep = history[len(history) - HISTORY_WINDOW :]
# Build a lightweight summary via LLM
llm, _model_name = await get_llm()
summary_prompt = (
"Ringkas percakapan berikut menjadi satu paragraf singkat dalam Bahasa Indonesia "
"yang mencakup topik utama dan data penting yang dibahas. "
"Hilangkan basa-basi, fokus pada fakta statistik dan permintaan user.\n\n"
+ "\n".join(
f"[{type(m).__name__}]: {getattr(m, 'content', '')[:300]}"
for m in to_compress
if not isinstance(m, SystemMessage)
)
)
try:
summary_response = await invoke_with_fallback(llm, [HumanMessage(content=summary_prompt)], config=config)
summary_text = (
summary_response.content
if hasattr(summary_response, "content")
else str(summary_response)
)
summary_message = SystemMessage(
content=f"[Ringkasan percakapan sebelumnya]: {summary_text}"
)
rebuilt = ([system_msg] if system_msg else []) + [summary_message] + to_keep
except Exception as e:
print(f"⚠️ history_trim_node summarization failed, falling back to safe_trim: {e}")
rebuilt = safe_trim(messages, limit=HISTORY_WINDOW)
# Replace the entire messages list β€” use a sentinel to signal a full overwrite.
# LangGraph merges with operator.add, so we need the state-replace trick:
# Return the new list but tagged so the reducer treats it as replacement.
# Simplest safe approach: return the same key; the graph will concatenate,
# so instead we store the rebuilt list back and return a no-op delta here.
# ⚑ Implementation note: LangGraph Annotated[list, operator.add] always
# *appends*. To truly replace we'd need a custom reducer. Instead we just
# pass a trimmed copy to the agent_node via a new state key.
# For now: return empty delta (history already present in state); the
# agent_node will call safe_trim on the raw state, which is sufficient.
# Mark as done with a lightweight no-op.
_ = rebuilt # rebuilt is computed but used as a reference for future upgrade
return {} # No-op β€” agent_node still trims via safe_trim()
# Define Nodes
async def intent_node(state: AgentState, config: RunnableConfig):
"""
Runs ONCE per request β€” classifies user intent and stores the tool list
into state["selected_tools"] so agent_node can reuse it without re-running.
"""
messages = state["messages"]
last_human = next(
(m for m in reversed(messages) if isinstance(m, HumanMessage)),
None,
)
if last_human:
query_text = last_human.content if isinstance(last_human.content, str) else str(last_human.content)
intent = classify_intent(query_text)
# selected_tools = get_tools_for_intent(intent)
# print(f" [INTENT] {intent} β†’ tools: {[t.name for t in selected_tools]}")
else:
# from .tools import tools as all_tools
# selected_tools = all_tools
intent = "UNKNOWN"
print(" [INTENT] UNKNOWN (no human message) β†’ tools: all")
# return {"selected_tools": selected_tools}
return {"intent": intent}
async def agent_node(state: AgentState, config: RunnableConfig):
raw_messages = state['messages']
# --- MESSAGE TRIMMING (Context Window Management) ---
trimmed_messages = safe_trim(raw_messages, limit=HISTORY_WINDOW)
llm, _model_name = await get_llm()
# --- CYCLE DETECTION ---
# If the last message is a ToolMessage, this is the second call (summarization cycle).
# In this case we must NOT bind tools β€” just let the model respond freely.
last_msg = trimmed_messages[-1] if trimmed_messages else None
is_post_tool = isinstance(last_msg, ToolMessage)
if is_post_tool:
# Cycle 2: model summarizes tool output β€” no tools bound
model = llm
else:
# Cycle 1: read pre-classified tools from state
intent = state.get("intent", "UNKNOWN")
selected_tools = get_tools_for_intent(intent)
model = llm.bind_tools(selected_tools) if selected_tools else llm
# Prepend system message if not present
if not trimmed_messages or not isinstance(trimmed_messages[0], SystemMessage):
trimmed_messages = [SystemMessage(content=SYSTEM_PROMPT)] + trimmed_messages
# Use invoke_with_fallback for auto quota-error recovery
response = await invoke_with_fallback(model, trimmed_messages, config=config)
if response.tool_calls:
return {"messages": [response]}
# Check if response is empty
if not response.content and not response.tool_calls:
from langchain_core.messages import AIMessage
return {"messages": [AIMessage(content="Maaf, saya mengalami kesulitan memproses permintaan Anda. Bisakah Anda coba lagi dengan pertanyaan yang lebih spesifik?")]}
return {"messages": [response]}
# Use prebuilt ToolNode β€” must contain ALL tools so any tool call can be executed
tool_node = ToolNode(tools)
# Define Conditional Logic
def should_continue(state: AgentState):
messages = state['messages']
last_message = messages[-1]
if not last_message.tool_calls or last_message.type == "tool":
return "end"
else:
return "continue"
# Build Graph
workflow = StateGraph(AgentState)
# intent_node runs first (1x per request) β†’ history_trim β†’ agent
workflow.add_node("intent", intent_node)
workflow.add_node("history_trim", history_trim_node)
workflow.add_node("agent", agent_node)
workflow.add_node("tools", tool_node)
# Entry point: intent classification always runs first
workflow.set_entry_point("intent")
# intent β†’ history_trim β†’ agent (initial call)
workflow.add_edge("intent", "history_trim")
workflow.add_edge("history_trim", "agent")
workflow.add_conditional_edges(
"agent",
should_continue,
{
"continue": "tools",
"end": END
}
)
# After tool execution: go directly back to agent (skip intent + history_trim)
# so intent classifier does NOT run again in cycle 2
workflow.add_edge("tools", "agent")
from langgraph.checkpoint.memory import MemorySaver
# Initialize Memory
memory = MemorySaver()
app = workflow.compile(
checkpointer=memory,
debug=False,
)
# Set recursion limit in config
app.config = {"recursion_limit": 50}