File size: 8,891 Bytes
eff58d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph.message import add_messages
from scripts.load_model import get_model
from typing import TypedDict, Literal, Optional, Annotated
from langgraph.graph import StateGraph, END
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
from scripts.prompts import (
    GENERAL_CHAT_SYSTEM_PROMPT,
    CODE_AGENT_SYSTEM_PROMPT,
    REPAIR_SYSTEM_PROMPT
)

# =========================================================
# LLM
# =========================================================
llm = get_model()


# =========================================================
# STATE
# =========================================================
class ChatState(TypedDict):
    user_input: Annotated[list[BaseMessage], add_messages]
    intent: Optional[Literal["coding", "general_chat"]]
    task_type: Optional[Literal["code_generation", "debugging", "explanation"]]
    language: Optional[Literal["python", "javascript", "cpp", "sql", "java", "unknown"]]
    generated_output: Optional[str]
    is_code: Optional[bool]
    retry_count: int


# =========================================================
# HELPERS
# =========================================================
def get_last_user_message(state: ChatState) -> str:
    messages = state["user_input"]

    if not messages:
        return ""

    return messages[-1].content


# =========================================================
# INTENT CLASSIFIER
# =========================================================
def classify_intent(state: ChatState):
    query = get_last_user_message(state).lower()

    coding_keywords = [
        "code", "python", "javascript", "java", "c++", "sql",
        "bug", "debug", "fix", "function", "algorithm",
        "class", "implement", "build", "api", "query",
        "optimize", "refactor", "script", "program"
    ]

    intent = "coding" if any(word in query for word in coding_keywords) else "general_chat"

    return {"intent": intent}


def route_intent(state: ChatState):
    if state["intent"] == "general_chat":
        return "general_chat"

    return "coding"


# =========================================================
# GENERAL CHAT
# =========================================================
def handle_general_chat(state: ChatState):
    query = get_last_user_message(state)

    messages = [
        SystemMessage(content=GENERAL_CHAT_SYSTEM_PROMPT),
        HumanMessage(content=query)
    ]

    response = llm.invoke(messages)

    return {
        "generated_output": response.content
    }


# =========================================================
# TASK CLASSIFIER
# =========================================================
def classify_task(state: ChatState):
    query = get_last_user_message(state).lower()

    debugging_keywords = [
        "fix", "debug", "error", "broken",
        "issue", "not working", "exception", "traceback"
    ]

    explanation_keywords = [
        "explain", "what is", "how does", "why", "difference between"
    ]

    if any(word in query for word in debugging_keywords):
        task = "debugging"

    elif any(word in query for word in explanation_keywords):
        task = "explanation"

    else:
        task = "code_generation"

    return {"task_type": task}


# =========================================================
# LANGUAGE DETECTOR
# =========================================================
def detect_language(state: ChatState):
    query = get_last_user_message(state).lower()

    if any(k in query for k in ["python", "def ", "import ", "print("]):
        lang = "python"

    elif any(k in query for k in ["javascript", "js", "function ", "console.log", "const ", "let "]):
        lang = "javascript"

    elif any(k in query for k in ["c++", "#include", "std::", "cout"]):
        lang = "cpp"

    elif any(k in query for k in ["java", "public class", "system.out"]):
        lang = "java"

    elif any(k in query for k in ["sql", "select ", "insert ", "update ", "delete ", "join "]):
        lang = "sql"

    else:
        lang = "unknown"

    return {"language": lang}


# =========================================================
# GENERATOR
# =========================================================
def generate_code(state: ChatState):
    query = get_last_user_message(state)

    task = state["task_type"]
    language = state["language"]

    messages = [
        SystemMessage(content=CODE_AGENT_SYSTEM_PROMPT),
        HumanMessage(content=f"""

Task Type: {task}

Requested Language: {language}



User Request:

{query}

""")
    ]

    response = llm.invoke(messages)

    return {
        "generated_output": response.content
    }


# =========================================================
# OUTPUT CLASSIFIER
# =========================================================
def classify_output(state: ChatState):
    output = (state["generated_output"] or "").lower()

    code_markers = [
        "def ", "class ", "function ", "const ", "let ",
        "#include", "std::", "public class", "system.out",
        "select ", "insert ", "update ", "delete ",
        "console.log", "print(", "fn "
    ]

    is_code = any(marker in output for marker in code_markers)

    return {
        "is_code": is_code
    }


# =========================================================
# ROUTER
# =========================================================
def route_output(state: ChatState):
    if state["task_type"] == "explanation":
        return "final"

    if state["is_code"]:
        return "final"

    if state["retry_count"] >= 2:
        return "final"

    return "repair"


# =========================================================
# REPAIR
# =========================================================
def repair_code(state: ChatState):
    bad_output = state["generated_output"] or ""
    language = state["language"]

    messages = [
        SystemMessage(content=REPAIR_SYSTEM_PROMPT),
        HumanMessage(content=f"""

The previous response was expected to be executable code but was not.



Requested language:

{language}



Bad output:

{bad_output}



Return ONLY executable code.

No explanation.

No markdown.

""")
    ]

    response = llm.invoke(messages)

    return {
        "generated_output": response.content,
        "retry_count": state["retry_count"] + 1
    }


# =========================================================
# GRAPH
# =========================================================
checkpointer = MemorySaver()
builder = StateGraph(ChatState)

builder.add_node("classify_intent", classify_intent)
builder.add_node("general_chat", handle_general_chat)
builder.add_node("classify_task", classify_task)
builder.add_node("detect_language", detect_language)
builder.add_node("generate_code", generate_code)
builder.add_node("classify_output", classify_output)
builder.add_node("repair", repair_code)

builder.set_entry_point("classify_intent")

builder.add_conditional_edges(
    "classify_intent",
    route_intent,
    {
        "general_chat": "general_chat",
        "coding": "classify_task"
    }
)

builder.add_edge("general_chat", END)

builder.add_edge("classify_task", "detect_language")
builder.add_edge("detect_language", "generate_code")
builder.add_edge("generate_code", "classify_output")

builder.add_conditional_edges(
    "classify_output",
    route_output,
    {
        "final": END,
        "repair": "repair"
    }
)

builder.add_edge("repair", "classify_output")

graph = builder.compile(checkpointer=checkpointer)


# =========================================================
# STREAM
# =========================================================
def stream_chat_response(user_message: str, thread_id: str):
    config = {"configurable": {"thread_id": thread_id}}

    initial_state = {
        "user_input": [HumanMessage(content=user_message)],
        "intent": None,
        "task_type": None,
        "language": None,
        "generated_output": None,
        "is_code": None,
        "retry_count": 0
    }

    for chunk in graph.stream(
        initial_state,
        config=config,
        stream_mode="messages"
    ):
        yield chunk


def get_chat_metadata(thread_id: str):
    config = {"configurable": {"thread_id": thread_id}}

    state = graph.get_state(config)
    values = state.values

    return {
        "intent": values.get("intent"),
        "task_type": values.get("task_type"),
        "language": values.get("language"),
        "is_code": values.get("is_code"),
        "retry_count": values.get("retry_count")
    }