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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langgraph.graph import StateGraph, END, START
|
| 2 |
+
from langgraph.checkpoint.memory import MemorySaver
|
| 3 |
+
from typing_extensions import TypedDict
|
| 4 |
+
from typing import Annotated, Dict, Any, List
|
| 5 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 6 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 7 |
+
from langchain_core.runnables import Runnable
|
| 8 |
+
from langchain.chat_models import ChatOpenAI # Or ChatGroq, ChatTogether
|
| 9 |
+
|
| 10 |
+
# -------------------
|
| 11 |
+
# Define State
|
| 12 |
+
# -------------------
|
| 13 |
+
class State(TypedDict):
|
| 14 |
+
messages: Annotated[List, lambda x: isinstance(x, list)]
|
| 15 |
+
answers: Annotated[List, lambda x: isinstance(x, list)]
|
| 16 |
+
retry_count: int
|
| 17 |
+
questions: Annotated[List, lambda x: isinstance(x, list)] # added
|
| 18 |
+
code: str
|
| 19 |
+
explanation: str
|
| 20 |
+
task_plan: str
|
| 21 |
+
user_input: str
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# -------------------
|
| 25 |
+
# Initialize LLM
|
| 26 |
+
# -------------------
|
| 27 |
+
# llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0) # Replace with ChatGroq or Together if needed
|
| 28 |
+
question_model = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0.7)
|
| 29 |
+
|
| 30 |
+
llm_agent_model = ChatTogether(model="mistralai/Mistral-7B-Instruct-v0.1")
|
| 31 |
+
|
| 32 |
+
code_model = ChatTogether(model="deepseek-ai/deepseek-coder-6.7b-instruct")
|
| 33 |
+
|
| 34 |
+
confirm_model = ChatGroq(model="qwen/qwen3-32b")
|
| 35 |
+
|
| 36 |
+
explain_model = ChatGroq(model="meta-llama/llama-guard-4-12b")
|
| 37 |
+
# -------------------
|
| 38 |
+
# Define Node Functions
|
| 39 |
+
# -------------------
|
| 40 |
+
def llm_agent(state: State) -> State:
|
| 41 |
+
messages = [
|
| 42 |
+
SystemMessage(content="You are an AI task planner. Break down user instructions."),
|
| 43 |
+
HumanMessage(content=state["user_input"])
|
| 44 |
+
]
|
| 45 |
+
response = llm_agent_model.invoke(messages)
|
| 46 |
+
state["task_plan"] = response.content
|
| 47 |
+
return state
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def generate_questions(state: State) -> State:
|
| 51 |
+
messages = [
|
| 52 |
+
SystemMessage(content="You generate follow-up questions to clarify vague instructions."),
|
| 53 |
+
HumanMessage(content=state["answers"][0])
|
| 54 |
+
]
|
| 55 |
+
response = question_model.invoke(messages)
|
| 56 |
+
state["questions"] = response.content
|
| 57 |
+
return state
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def generate_code(state: State) -> State:
|
| 61 |
+
messages = [
|
| 62 |
+
SystemMessage(content="You are a coding expert. Generate clean, well-documented Python code."),
|
| 63 |
+
HumanMessage(content=state["answers"][0])
|
| 64 |
+
]
|
| 65 |
+
response = code_model.invoke(messages)
|
| 66 |
+
state["code"] = response.content
|
| 67 |
+
return state
|
| 68 |
+
|
| 69 |
+
def handle_answers(state: State) -> State:
|
| 70 |
+
print("Handling answers...")
|
| 71 |
+
|
| 72 |
+
answer = state["answers"][0]
|
| 73 |
+
system_prompt = "You are a helpful assistant that confirms the received idea."
|
| 74 |
+
user_msg = f"The user said: '{answer}'. Confirm and move ahead."
|
| 75 |
+
|
| 76 |
+
response = confirm_model.invoke([
|
| 77 |
+
SystemMessage(content=system_prompt),
|
| 78 |
+
HumanMessage(content=user_msg)
|
| 79 |
+
])
|
| 80 |
+
|
| 81 |
+
state["messages"].append(response.content.strip())
|
| 82 |
+
return state
|
| 83 |
+
|
| 84 |
+
def explain_code(state: State) -> State:
|
| 85 |
+
print("Explaining code...")
|
| 86 |
+
|
| 87 |
+
code = state["code"]
|
| 88 |
+
system_prompt = "You are a Python tutor. Explain what the following code does in simple terms."
|
| 89 |
+
user_msg = f"Code:\n{code}"
|
| 90 |
+
|
| 91 |
+
response = explain_model.invoke([
|
| 92 |
+
SystemMessage(content=system_prompt),
|
| 93 |
+
HumanMessage(content=user_msg)
|
| 94 |
+
])
|
| 95 |
+
|
| 96 |
+
state["explanation"] = response.content.strip()
|
| 97 |
+
return state
|
| 98 |
+
|
| 99 |
+
def wait_for_answers(state: State) -> State:
|
| 100 |
+
print("Waiting for answers...")
|
| 101 |
+
|
| 102 |
+
state["retry_count"] = state.get("retry_count", 0) + 1
|
| 103 |
+
|
| 104 |
+
# Simulate receiving an answer after 2 retries
|
| 105 |
+
if state["retry_count"] >= 2:
|
| 106 |
+
state["answers"] = ["Build a calculator app"]
|
| 107 |
+
return state
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# -------------------
|
| 111 |
+
# Define Condition Function
|
| 112 |
+
# -------------------
|
| 113 |
+
|
| 114 |
+
MAX_RETRIES = 3
|
| 115 |
+
|
| 116 |
+
def check_if_answered(state: State) -> str:
|
| 117 |
+
if "answers" in state and state["answers"]:
|
| 118 |
+
return "answered"
|
| 119 |
+
elif state.get("retry_count", 0) >= MAX_RETRIES:
|
| 120 |
+
print("Max retries reached. Proceeding anyway.")
|
| 121 |
+
return "answered"
|
| 122 |
+
else:
|
| 123 |
+
return "not_answered"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# -------------------
|
| 127 |
+
# Build the Graph
|
| 128 |
+
# -------------------
|
| 129 |
+
|
| 130 |
+
builder = StateGraph(State)
|
| 131 |
+
|
| 132 |
+
builder.add_node("LLM_Agent", llm_agent)
|
| 133 |
+
builder.add_node("Generate_Questions", generate_questions)
|
| 134 |
+
builder.add_node("Wait_For_Answers", wait_for_answers)
|
| 135 |
+
builder.add_node("Handle_Answers", handle_answers)
|
| 136 |
+
builder.add_node("Generate_Code", generate_code)
|
| 137 |
+
builder.add_node("Code_Explainer", explain_code)
|
| 138 |
+
|
| 139 |
+
builder.set_entry_point("LLM_Agent")
|
| 140 |
+
|
| 141 |
+
builder.add_edge("LLM_Agent", "Generate_Questions")
|
| 142 |
+
builder.add_conditional_edges(
|
| 143 |
+
"Generate_Questions",
|
| 144 |
+
check_if_answered,
|
| 145 |
+
{
|
| 146 |
+
"answered": "Handle_Answers",
|
| 147 |
+
"not_answered": "Wait_For_Answers"
|
| 148 |
+
}
|
| 149 |
+
)
|
| 150 |
+
builder.add_edge("Wait_For_Answers", "Generate_Questions")
|
| 151 |
+
builder.add_edge("Handle_Answers", "Generate_Code")
|
| 152 |
+
builder.add_edge("Generate_Code", "Code_Explainer")
|
| 153 |
+
builder.add_edge("Code_Explainer", END)
|
| 154 |
+
|
| 155 |
+
# -------------------
|
| 156 |
+
# Compile and Run
|
| 157 |
+
# -------------------
|
| 158 |
+
|
| 159 |
+
memory = MemorySaver()
|
| 160 |
+
graph = builder.compile(checkpointer=memory)
|
| 161 |
+
|
| 162 |
+
inputs = {"messages": [], "answers": [], "retry_count": 0, "code": "", "explanation": "", "questions": [], "task_plan" :"","user_input": "I want to create an agent"}
|
| 163 |
+
|
| 164 |
+
for step in graph.stream(inputs):
|
| 165 |
+
for key, val in step.items():
|
| 166 |
+
print(f"\n--- {key} ---\n{val}")
|