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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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
from langgraph.graph import StateGraph, MessagesState, END, START
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.messages import SystemMessage
from langgraph.checkpoint.memory import MemorySaver
from langchain_community.document_loaders import WikipediaLoader
from langchain_experimental.utilities.python import PythonREPL

from pinecone import Pinecone

from typing import List, Annotated
from pydantic import BaseModel, Field
from IPython.display import Image, display
import operator
import prompts

# set environment variables
import os
from dotenv import load_dotenv

load_dotenv()

llm = ChatOpenAI(model="gpt-4o", temperature=0)
weak_llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.5)


class QuestionState(MessagesState):
    topic: str  # topic of the question
    subtopic: str  # subtopic of the question
    difficulty: str  # difficulty of the question
    description: str  # description of the subtopic
    context: Annotated[list, operator.add]  # knowledge base of the subtopic
    relevant_questions: List[dict]  # relevant questions
    num_questions: int  # number of relevant questions to extract
    human_feedback: str  # feedback from the human
    question: str  # question to ask
    steps: List[str]  # steps to solve the question
    tool_requests: List[dict]  # tool requests to solve the question
    tool_results: List[dict]  # tool results to solve the question
    verified: bool  # if the solution is verified
    solution: str  # solution to the question
    answer: str  # answer to the question


# -------------------------------
# Node 1: Generate Description Node
# -------------------------------
def generate_description(state: QuestionState):
    """
    Generate a description for the subtopic
    """
    topic = state["topic"]
    subtopic = state["subtopic"]

    # generate description
    system_message = prompts.DESCRIPTION_INSTRUCTION.format(
        topic=topic, subtopic=subtopic
    )
    description = weak_llm.invoke(
        [SystemMessage(content=system_message)], max_tokens=30
    ).content

    # write description to state
    return {"description": description}


# -------------------------------
# Node 2: Search Wikipedia Node
# -------------------------------
def search_wikipedia(state: QuestionState):
    """
    Search wikipedia for the topic and subtopic
    """

    subtopic = state["subtopic"]

    search_query = f"What is {subtopic}"

    # search wikipedia
    search_docs = WikipediaLoader(
        query=search_query, load_max_docs=1, doc_content_chars_max=1500
    ).load()

    # Format
    formatted_search_docs = "\n\n---\n\n".join(
        [
            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
            for doc in search_docs
        ]
    )

    return {"context": [formatted_search_docs]}


# -------------------------------
# Node 3: Search Document Node
# -------------------------------
def search_document(state: QuestionState):
    """
    Search the document for relevant context
    """

    topic = state["topic"]
    subtopic = state["subtopic"]

    # Initialize OpenAI Embeddings client
    client = OpenAIEmbeddings(model="text-embedding-3-large")

    query = f"Search about {topic} in area of {subtopic}"
    embedded_query = client.embed_query(query)

    # Initialize Pinecone client
    api_key = os.environ.get("PINECONE_API_KEY")
    pc = Pinecone(api_key=api_key)

    # 2. Vector DB query with metadata filter
    index_name = os.environ.get("PINECONE_INDEX_NAME")
    index = pc.Index(index_name)

    filters = {
        "topic": {"$eq": topic},
        "subtopic": {"$eq": subtopic},
        "type": {"$eq": "description"},
    }

    # Execute similarity search
    try:
        results = index.query(
            vector=embedded_query,
            filter=filters,
            top_k=1,  # Get top 5 similar questions
            include_metadata=True,
        )
    except Exception as e:
        raise ConnectionError(f"Vector DB query failed: {str(e)}")

    # Get the context
    if results and hasattr(results, "matches") and len(results.matches) > 0:
        context = results.matches[0].metadata.get("context", "")
        return {"context": [context]}
    else:
        return {"context": []}


# -------------------------------
# Node 4: Search Questions Node
# -------------------------------
def search_questions(state: QuestionState):
    """
    Search the document for relevant questions
    """

    topic = state["topic"]
    subtopic = state["subtopic"]
    num_questions = state["num_questions"]
    difficulty = state["difficulty"]

    # Initialize OpenAI Embeddings client
    client = OpenAIEmbeddings(model="text-embedding-3-large")

    query = f"Questions related to {topic} in area of {subtopic}"
    embedded_query = client.embed_query(query)

    # Initialize Pinecone client
    api_key = os.environ.get("PINECONE_API_KEY")
    pc = Pinecone(api_key=api_key)

    # 2. Vector DB query with metadata filter
    index_name = os.environ.get("PINECONE_INDEX_NAME")
    index = pc.Index(index_name)

    filters = {
        "topic": {"$eq": topic},
        "subtopic": {"$eq": subtopic},
        "type": {"$eq": "question"},
        "difficulty": {"$eq": difficulty},
    }

    # Execute similarity search
    try:
        results = index.query(
            vector=embedded_query,
            filter=filters,
            top_k=num_questions,
            include_metadata=True,
        )
    except Exception as e:
        raise ConnectionError(f"Vector DB query failed: {str(e)}")

    references = []
    for match in results.matches:
        metadata = match.metadata
        references.append(
            {
                "question": metadata["question"],
                "answer": metadata["answer"],
                "difficulty": metadata["difficulty"],
            }
        )

    return {"relevant_questions": references}


# -------------------------------
# Node 5: Generate Question Node
# -------------------------------
def generate_question(state: QuestionState):
    """
    Generate a question for the subtopic
    """
    topic = state["topic"]
    subtopic = state["subtopic"]
    difficulty = state["difficulty"]
    context = state["context"]
    relevant_questions = state["relevant_questions"]
    human_feedback = state.get("human_feedback", "")

    # generate question
    query = prompts.QUESTION_INSTRUCTION.format(
        topic=topic,
        subtopic=subtopic,
        difficulty=difficulty,
        context=context,
        relevant_questions=relevant_questions,
        feedback=human_feedback,
    )
    question = llm.invoke([SystemMessage(content=query)], temperature=0.3).content

    # Clean residual markdown formatting
    question = question.strip().strip("`").replace("**Question:**", "").strip()

    print("Generated Question: ", question)
    # write question to state
    return {"question": question}


# -------------------------------
# Node 6: Feedback Node
# -------------------------------
def human_feedback(state: QuestionState):
    """No-op node that shoulds be interrupted on"""
    print("Human Feedback Node: ", state)
    pass


def should_continue(state: QuestionState):
    """Return the next node to execute"""
    print("Should Continue: ", state)
    # Check if human feedback
    human_feedback = state.get("human_feedback", None)
    if human_feedback:
        return "generate_question"

    # Otherwise end
    return "llm_step_planner"


# -------------------------------
# Node 7: LLM Step Planner
# -------------------------------
class SolutionPlan(BaseModel):
    solution_steps: List[str] = Field(description="List of steps to solve the problem")


def llm_step_planner(state: QuestionState):
    question = state["question"]
    try:
        prompt = prompts.STEP_INSTRUCTION.format(question=question)
        structured_llm = llm.with_structured_output(SolutionPlan)
        steps = structured_llm.invoke([SystemMessage(content=prompt)])
        print("Steps", steps)

        return {"steps": steps.solution_steps}

    except Exception as e:
        return {"error": f"LLM Parsing Error: {str(e)}"}


# -------------------------------
# Node 8: LLM Tool Decider
# -------------------------------
class ToolRequest(BaseModel):
    code: str = Field(description="Python code to execute")
    description: str = Field(description="Description of the code")


class ToolRequestList(BaseModel):
    tool_requests: List[ToolRequest] = Field(description="List of tool requests")


def llm_tool_decider(state: QuestionState):
    if "error" in state and state["error"]:
        return state  # Pass through error

    try:
        question = state["question"]
        steps = state.get("steps", [])

        prompt = prompts.TOOL_INSTRUCTION.format(question=question, steps=steps)

        structured_llm = llm.with_structured_output(ToolRequestList)
        tool_requests = structured_llm.invoke(
            [SystemMessage(content=prompt)], max_tokens=500, temperature=0.2
        )
        print("Tool Requests", tool_requests)
        return {
            "tool_requests": [req.model_dump() for req in tool_requests.tool_requests]
        }
    except Exception as e:
        return {"error": f"LLM Tool Decider Error: {str(e)}"}


# -------------------------------
# Node 9: LLM Tool Executor
# -------------------------------
code_executor = PythonREPL()


def tool_executor(state: QuestionState):
    if "error" in state and state["error"]:
        return state

    try:
        tool_results = []
        for req in state.get("tool_requests", []):
            print("Req", req)
            if req.get("type", "sympy") == "sympy":  # default to sympy
                try:
                    output = code_executor.run(req["code"])  # Executes full code
                    tool_results.append(
                        {
                            "description": req.get("description", ""),
                            "result": output.strip(),
                        }
                    )
                except Exception as e:
                    tool_results.append(
                        {
                            "description": req.get("description", ""),
                            "result": f"Execution Error: {str(e)}",
                        }
                    )
            else:
                tool_results.append(
                    {
                        "description": f"Unknown tool type: {req.get('type')}",
                        "result": None,
                    }
                )
        print("Tool Results", tool_results)
        return {"tool_results": tool_results}
    except Exception as e:
        return {"error": f"Tool Execution Error: {str(e)}"}


# -------------------------------
# Node 10: LLM Verifier
# -------------------------------
class VerifierResponse(BaseModel):
    verified: bool = Field(description="Whether the solution is verified")
    explanation: str = Field(description="Explanation for verification decision")


def llm_verifier(state: QuestionState):
    if "error" in state and state["error"]:
        return state

    try:
        question = state["question"]
        steps = state.get("steps", [])
        tool_results = state.get("tool_results", [])

        prompt = prompts.VERIFICATION_INSTRUCTION.format(
            question=question, steps=steps, tool_results=tool_results
        )

        structured_llm = weak_llm.with_structured_output(VerifierResponse)
        verification_results = structured_llm.invoke(
            [SystemMessage(content=prompt)], max_tokens=500
        ).model_dump()
        result = False
        if verification_results.get("verified", False):
            result = True
        else:
            result = False
        return {
            "verified": result,
            "error": (
                None
                if result
                else f"Verification Failed: {verification_results.get('explanation', 'No explanation')}"
            ),
        }
    except Exception as e:
        return {"error": f"LLM Verifier Error: {str(e)}"}


# -------------------------------
# Node 11: LLM Finalizer
# -------------------------------
class FinalizerResponse(BaseModel):
    solution: str = Field(description="Markdown solution")
    answer: str = Field(description="Final answer")


def llm_finalizer(state: QuestionState):
    if "error" in state and state["error"]:
        state["solution"] = f"### Error\n{state['error']}"
        state["answer"] = "N/A"
        return state

    try:
        question = state["question"]
        steps = state.get("steps", [])
        tool_results = state.get("tool_results", [])
        verified = state.get("verified", False)

        prompt = prompts.FINALIZE_INSTRUCTION.format(
            question=question,
            steps=steps,
            tool_results=tool_results,
            verified=verified,
        )
        structured_llm = llm.with_structured_output(FinalizerResponse)
        final_response = structured_llm.invoke(
            [SystemMessage(content=prompt)], max_tokens=1000, temperature=0.2
        )

        return {"solution": final_response.solution, "answer": final_response.answer}
    except Exception as e:
        return {"solution": f"### Finalization Error\n{str(e)}", "answer": "N/A"}


# -------------------------------
# Graph Construction
# -------------------------------
builder = StateGraph(QuestionState)
builder.add_node("generate_description", generate_description)
# builder.add_node("search_wikipedia", search_wikipedia)
builder.add_node("search_document", search_document)
builder.add_node("search_questions", search_questions)
builder.add_node("generate_question", generate_question)
builder.add_node("feedback", human_feedback)
builder.add_node("llm_step_planner", llm_step_planner)
builder.add_node("llm_tool_decider", llm_tool_decider)
builder.add_node("tool_executor", tool_executor)
builder.add_node("llm_verifier", llm_verifier)
builder.add_node("llm_finalizer", llm_finalizer)

# Add edges
builder.add_edge(START, "generate_description")
# builder.add_edge("generate_description", "search_wikipedia")
builder.add_edge("generate_description", "search_document")
builder.add_edge("generate_description", "search_questions")
# builder.add_edge("search_wikipedia", "generate_question")
builder.add_edge("search_document", "generate_question")
builder.add_edge("search_questions", "generate_question")
builder.add_edge("generate_question", "feedback")
builder.add_conditional_edges(
    "feedback", should_continue, ["generate_question", "llm_step_planner"]
)
# builder.add_edge("generate_question", "llm_step_planner")
builder.add_edge("llm_step_planner", "llm_tool_decider")
builder.add_edge("llm_tool_decider", "tool_executor")
builder.add_edge("tool_executor", "llm_verifier")
builder.add_edge("llm_verifier", "llm_finalizer")
builder.add_edge("llm_finalizer", END)

# Compile
memory = MemorySaver()
question_graph = builder.compile(interrupt_before=["feedback"], checkpointer=memory)
question_graph.name = "QuestionGenerationGraph"
# question_graph = builder.compile(checkpointer=memory)

# display(Image(question_graph.get_graph(xray=1).draw_mermaid_png()))