File size: 6,304 Bytes
07d1ce5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LangGraph workflow for the research assistant.

Why LangGraph instead of a plain LCEL chain?
A research-answering task isn't strictly linear: depending on what the
retriever returns we may want to rewrite the query, retrieve more, or
generate. LangGraph models this as a state machine with explicit nodes
and conditional edges β€” easier to reason about, easier to add nodes,
and built-in support for streaming intermediate state to the UI.

Flow:
    rewrite_query β†’ retrieve β†’ grade β†’ generate β†’ reflect β†’ END
                                                       ↓
                                               (or back to retrieve once)
"""

from operator import add
from typing import Annotated, List, Optional, TypedDict

from langchain_core.documents import Document
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import END, StateGraph
from pydantic import BaseModel, Field

from src.llm import get_chat_llm, GENERATE_PROMPT, GRADE_PROMPT, REFLECT_PROMPT, REWRITE_QUERY_PROMPT
from src.retrieval import HybridRetriever
from src.utils import get_logger

log = get_logger(__name__)

MAX_REFLECTION_LOOPS = 1


# ── Schemas ───────────────────────────────────────────────────────────────────

class SearchQueries(BaseModel):
    search_queries: List[str] = Field(
        description="2-3 concise search queries derived from the user's question."
    )

class GradeDocument(BaseModel):
    relevant: bool = Field(
        description="True if the document is relevant to the question, False otherwise."
    )

class Reflection(BaseModel):
    sufficient: bool = Field(
        description="True if the draft answer fully addresses the question."
    )
    follow_up_query: Optional[str] = Field(
        default=None,
        description="A single focused search query to fill the gap, if insufficient.",
    )


# ── State ─────────────────────────────────────────────────────────────────────

class ResearchState(TypedDict, total=False):
    question: str
    search_queries: List[str]
    documents: Annotated[List[Document], add]
    answer: str
    reflection_count: int


# ── Helpers ───────────────────────────────────────────────────────────────────

def _format_context(docs: List[Document]) -> str:
    return "\n\n".join(
        f"[{i + 1}] {d.metadata.get('title', d.metadata.get('url', 'source'))}\n{d.page_content}"
        for i, d in enumerate(docs)
    )


# ── Graph factory ─────────────────────────────────────────────────────────────

def build_graph(retriever: HybridRetriever):
    """Compile and return a runnable LangGraph workflow."""
    llm = get_chat_llm()

    def rewrite_query(state: ResearchState) -> ResearchState:
        structured_llm = llm.with_structured_output(SearchQueries)
        result = structured_llm.invoke([
            SystemMessage(content=REWRITE_QUERY_PROMPT),
            HumanMessage(content=state["question"]),
        ])
        log.info("rewrote_queries", queries=result.search_queries)
        return {"search_queries": result.search_queries or [state["question"]]}

    def retrieve(state: ResearchState) -> ResearchState:
        all_docs: List[Document] = []
        for q in state.get("search_queries", [state["question"]]):
            all_docs.extend(retriever.retrieve(q))
        return {"documents": all_docs}

    def grade(state: ResearchState) -> ResearchState:
        grader = llm.with_structured_output(GradeDocument)
        kept: List[Document] = []
        for doc in state["documents"]:
            result = grader.invoke([
                SystemMessage(content=GRADE_PROMPT),
                HumanMessage(content=f"Question: {state['question']}\n\nDocument:\n{doc.page_content}"),
            ])
            if result.relevant:
                kept.append(doc)
        log.info("graded", kept=len(kept), total=len(state["documents"]))
        return {"documents": kept if kept else state["documents"][:3]}

    def generate(state: ResearchState) -> ResearchState:
        answer = llm.invoke([
            SystemMessage(content=GENERATE_PROMPT.format(context=_format_context(state["documents"]))),
            HumanMessage(content=state["question"]),
        ])
        return {"answer": answer.content}

    def reflect(state: ResearchState) -> ResearchState:
        reflector = llm.with_structured_output(Reflection)
        result = reflector.invoke([
            SystemMessage(content=REFLECT_PROMPT),
            HumanMessage(content=(
                f"Question: {state['question']}\n\n"
                f"Draft answer:\n{state['answer']}"
            )),
        ])
        count = state.get("reflection_count", 0) + 1

        if result.sufficient or not result.follow_up_query or count >= MAX_REFLECTION_LOOPS:
            return {"reflection_count": count}

        return {"reflection_count": count, "search_queries": [result.follow_up_query]}

    def should_continue(state: ResearchState) -> str:
        if state.get("reflection_count", 0) >= MAX_REFLECTION_LOOPS:
            return END
        if not state.get("search_queries"):
            return END
        return "retrieve"

    workflow = StateGraph(ResearchState)
    workflow.add_node("rewrite_query", rewrite_query)
    workflow.add_node("retrieve", retrieve)
    workflow.add_node("grade", grade)
    workflow.add_node("generate", generate)
    workflow.add_node("reflect", reflect)

    workflow.set_entry_point("rewrite_query")
    workflow.add_edge("rewrite_query", "retrieve")
    workflow.add_edge("retrieve", "grade")
    workflow.add_edge("grade", "generate")
    workflow.add_edge("generate", "reflect")
    workflow.add_conditional_edges("reflect", should_continue, {"retrieve": "retrieve", END: END})

    return workflow.compile()