Generative AIby Dhruv Narang

Run It: Watch the Attempts

We start with a topic, an empty draft and attempt 0.

graph = StateGraph(State)

graph.add_node("writer",writer_node)
graph.add_node("reviewer",reviewer_node)

graph.add_edge(START , "writer")

graph.add_edge("writer","reviewer")

graph.add_conditional_edges("reviewer",quality_gate)


app = graph.compile()

initial_state = {
        "topic": topic,
        "draft": "",
        "reviewer_feedback": "",
        "is_approved": False,
        "attempt": 0,
}

res = app.invoke(initial_state)
Start
attempt is 0 and draft is empty. The first writer round makes attempt 1.
The result
invoke returns the final state: the last draft, the last feedback, is_approved and the number of attempts.
What to watch
Print res and look at attempt. If it is 1, the first draft passed. If it is 3, the loop hit its limit.
Rate limit
Your teaching plan notes that the free Mistral key allows only 2 requests per minute. This loop makes 2 calls per round, so it can stop with 429 Rate limit exceeded. Use a paid key, or slow the calls down.
The code is from your 01_iterative.py. We show no model output here, because we did not call the API.

Some topics need fresh facts. We give the writer a search tool.

The issue
A topic like “this year's AI news” needs fresh facts. The model's own memory is old.
The first try
The writer writes from memory.
Why it fails
The post may contain outdated or invented facts, and the reviewer cannot check them.
The fix
Give the writer a search tool. It can search first, read the results, and then write.
search_tool = TavilySearch(max_results = 3)
tools = [search_tool]
writter_llm_with_tools = writter_llm.bind_tools(tools)
tool_node = ToolNode(tools)

def should_use_tool(state:State):
    last_message = state['messages'][-1]

    if getattr(last_message,'tool_calls',None):
        return "tools"
    return "extract_draft"
STARTwritertoolsextract_draftreviewerENDtool callno more tool callsrejected: back to the writerapproved, or3 attemptsthe tool loopwriter and tools
The code is from your 02_iterative_tools.py. extract_draft pulls the final text out of the messages and puts it in draft, so the reviewer can read it.

Two Loops in One Graph

The new graph has a tool loop inside the review loop.

graph = StateGraph(State)

graph.add_node("writer",writer_node)
graph.add_node("tools",tool_node)
graph.add_node("extract_draft",extract_draft_node)
graph.add_node("reviewer",reviewer_node)

graph.add_edge(START ,"writer")

graph.add_conditional_edges("writer",should_use_tool)

# ReAct loop: tool results go back to the writer, which then writes the post (or searches again)
graph.add_edge("tools","writer")

graph.add_edge("extract_draft","reviewer")

graph.add_conditional_edges("reviewer",should_stop_looping)
LoopGoes betweenIt stops when…
Tool loop (inside)writer and toolsthe writer asks for no more tools: should_use_tool returns "extract_draft"
Review loop (outside)reviewer and writerapproved, or 3 attempts: should_stop_looping returns END
This graph is an agent. The model decides by itself whether to use a tool, and a loop keeps running until the job is done. It is the ReAct loop from the Tool Calling lesson, now inside a graph with a reviewer.

Quick Revision

The whole lesson on one page.

Loop
An edge back
A conditional edge sends the work back to an earlier node. That is all a loop is.
Stop rule
Always have one
Yours has two: approved, or 3 attempts. Without one, the loop can run for thousands of steps.
Tools plus loop
An agent
The writer can search, and the reviewer can send the work back. Two loops, one graph.
Code
Write and review loop01_iterative.py · 133 linesShow code
  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
from dotenv import load_dotenv
load_dotenv()


from langchain.chat_models import init_chat_model
from typing import TypedDict
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser , PydanticOutputParser
from pydantic import BaseModel , Field
from langgraph.graph import StateGraph , END , START
writter_llm = init_chat_model("mistralai:open-mistral-nemo" ,temperature=0.7)
reviewer_llm = init_chat_model("mistralai:open-mistral-nemo",temperature=0.3)
from rich import print

parser = StrOutputParser()
class State(TypedDict):
    topic:str
    draft:str
    reviewer_feedback:str
    is_approved:bool
    attempt:int

WRITER_SYSTEM_PROMPT = """You are an expert LinkedIn copywriter known for writing authentic, high-engagement posts.
Your goal is to write a publish-ready LinkedIn post based on the given topic.
Editorial Rules:
1. Strong, attention-grabbing hook in the very first line (no cheesy clichés).
2. Format: Easy to skim with short 1-2 sentence paragraphs and bullet points where helpful.
3. Length: Approximately 150 to 200 words.
4. Tone: Insightful, professional, yet conversational and human.
5. Ending: Conclude with a thought-provoking question to encourage comments.
6. Strict constraint: DO NOT use any hashtags."""

writter_prompt = ChatPromptTemplate.from_messages([
    ("system",WRITER_SYSTEM_PROMPT),
    ("human","""
        Topic:{topic}
        If is not first draft 
        this is previous Draft {draft}
        this is feedback of this draft {feedback}
        Instructions: 
        - If this is the first draft (no feedback), write an amazing fresh post.
        - If feedback is provided, carefully rewrite the draft to address EVERY critique while keeping the core message intact. 
    """)])


def writer_node(state:State)->dict:
    """Write the post on give topic and also improve if any feedback is there?"""
    attempt = state.get("attempt",0) +1
    chain = writter_prompt | writter_llm | parser
    response =  chain.invoke({
                        "topic":state["topic"],
                        "draft":state["draft"] ,
                        "feedback":state["reviewer_feedback"]})

    return {"draft":response,"attempt":attempt}


REVIEWER_SYSTEM_PROMPT = """You are a strict, world-class LinkedIn editor. You evaluate drafts with high standards.

Check against these 5 criteria:
1. Is the first line a strong hook?
2. Is it easy to skim (short paragraphs)?
3. Is it around 150-200 words?
4. Does it end with an engaging question?
5. Are there ZERO hashtags?

Approve only if all 5 criteria are met. Keep feedback to 1 or 2 concise sentences explaining what needs improvement or why it was approved."""

reviewer_prompt = ChatPromptTemplate.from_messages([
    ("system", REVIEWER_SYSTEM_PROMPT),
    ("human", "Evaluate this draft:\n\n{draft} of this {topic}")
])

class ReviewerFeedBack(BaseModel):
    is_approved : bool = Field(description="Weather Draft is approved or not")
    feedback:str=Field(description="Feedback of draft to improve")

# with_structured_output uses the provider's native JSON mode -> always returns a ReviewerFeedBack object
structured_reviewer = reviewer_llm.with_structured_output(ReviewerFeedBack)

def reviewer_node(state:State)->dict:
    draft = state["draft"]
    topic = state["topic"]
    chain = reviewer_prompt | structured_reviewer
    response = chain.invoke({"draft":draft,"topic":topic})

    return {"reviewer_feedback":response.feedback,"is_approved":response.is_approved }


"""Loop: reviewer -> back to writer until approved or 3 attempts"""
def quality_gate(state:State):
    if state["is_approved"]:
        return END
    elif state["attempt"] >=3:
        return END
    else:
        return "writer"


graph = StateGraph(State)

graph.add_node("writer",writer_node)
graph.add_node("reviewer",reviewer_node)

graph.add_edge(START , "writer")

graph.add_edge("writer","reviewer")

graph.add_conditional_edges("reviewer",quality_gate)


app = graph.compile()

topic = input("\nWhat topic do you want a LinkedIn post about?\n> ").strip()


initial_state = {
        "topic": topic,
        "draft": "",
        "reviewer_feedback": "",
        "is_approved": False,
        "attempt": 0,
}

res = app.invoke(initial_state)

print(res)

    
Loop with a search tool02_iterative_tools.py · 187 linesShow code
  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
from typing import TypedDict , Annotated
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langgraph.graph import StateGraph , START ,END
from langgraph.prebuilt import ToolNode
from langchain_tavily import TavilySearch
from langgraph.graph.message import add_messages
from langchain_core.messages import SystemMessage, HumanMessage, ToolMessage
from dotenv import load_dotenv

load_dotenv()

search_tool = TavilySearch(max_results = 3)


tools = [search_tool]

writter_llm = init_chat_model("mistralai:open-mistral-nemo" ,temperature=0.7) 
writter_llm_with_tools = writter_llm.bind_tools(tools)

reviewer_llm = init_chat_model("mistralai:open-mistral-nemo" , temperature=0.2)

class State(TypedDict):
    topic:str
    messages:Annotated[list,add_messages]
    draft :str
    review_feedback:str
    is_approved:bool
    attempt:int


WRITER_SYSTEM_PROMPT = (
    "You are an expert LinkedIn content writer. Your job is to write "
    "engaging, professional LinkedIn posts about the given topic. "
    "If the topic requires up-to-date information, statistics, or "
    "current trends, use the web search tool to gather fresh context "
    "before writing. If you have already received feedback on a "
    "previous draft, carefully address every point in the new draft. "
    "Rules for good LinkedIn posts: strong hook in the first line, "
    "1 clear takeaway, easy to skim (short paragraphs), around "
    "150–200 words, ends with a question or call-to-action to invite "
    "engagement. Do not use hashtags."
)


def writer_node(state:State) -> dict:
    """Writes (or rewrites) the LinkedIn post. Can call Tavily to search first."""
    history = state["messages"]

    # Coming back from the tools node: same attempt, LLM now reads the search results (ToolMessages)
    if history and isinstance(history[-1], ToolMessage):
        response = writter_llm_with_tools.invoke([SystemMessage(content=WRITER_SYSTEM_PROMPT)] + history)
        return {"messages":[response]}

    attempt = state.get("attempt",0)+1
    topic = state["topic"]
    previous_feedback = state['review_feedback']

    if attempt ==1:
        user_message = (
            f"Write a LinkedIn post on this topic: {topic}. "
            f"If you need current info, search the web first."
        )
    else:
        user_message = (
            f"Your previous draft on '{topic}' was rejected. "
            f"Here is the reviewer's feedback:\n\n{previous_feedback}\n\n"
            f"Write a new, improved draft that fixes every issue mentioned. "
            f"Do not repeat the same mistake."
        )
    human_message = HumanMessage(content=user_message)
    response = writter_llm_with_tools.invoke(
        [SystemMessage(content=WRITER_SYSTEM_PROMPT)] + history + [human_message]
    )

    return {
        "messages":[human_message,response],
        "attempt":attempt
    }

def extract_draft_node(state:State) -> dict:
    """After the writer finishes tool calls, pulls the final text out as the draft."""
    last_message = state['messages'][-1]
    draft = last_message.text  # .text works for both string and Gemini's list content
    print(f"\n\n generated post \n {draft} \n ")
    return {"draft" : draft}


REVIEWER_SYSTEM_PROMPT = (
    "You are a strict LinkedIn content reviewer. You judge whether a "
    "post is publish-ready. Evaluate against these criteria:\n"
    "1. Strong hook in the first line\n"
    "2. One clear, valuable takeaway\n"
    "3. Easy to skim — uses short paragraphs\n"
    "4. Roughly 150-200 words\n"
    "5. Ends with an engaging question or CTA\n"
    "6. Professional but human tone (not corporate-robotic)\n"
    "7. No hashtags\n\n"
    "Respond in exactly this format:\n"
    "VERDICT: APPROVED or REJECTED\n"
    "FEEDBACK: <one short paragraph explaining why>\n\n"
    "Be strict but fair. Approve only if the post genuinely meets all "
    "criteria. Reject if even one criterion is clearly missing."
)

tool_node = ToolNode(tools)

def reviewer_node(state:State)->dict:
    """Reviews the draft and decides: approve or reject with feedback."""
    draft = state["draft"]

    prompt = (
        f"review this LinkedIn post draft : \n"
        f"{draft}\n"
        f"give your reviews"
    )
    response =  reviewer_llm.invoke(
        [("system",REVIEWER_SYSTEM_PROMPT),("human",prompt)]
    )
    review_text = response.content.strip()
    is_approved ="APPROVED" in review_text.upper().split("FEEDBACK")[0]

    if "FEEDBACK:" in review_text:
        feedback = review_text.split("FEEDBACK:", 1)[1].strip()
    else:
        feedback = review_text

    return {
        "review_feedback": feedback,
        "is_approved": is_approved,
    }

"""ReAct loop: writer asks for a tool -> tools node runs it -> back to writer"""
def should_use_tool(state:State):
    last_message = state['messages'][-1]

    if getattr(last_message,'tool_calls',None):
        return "tools"
    return "extract_draft"

def should_stop_looping(state:State):
    if state['is_approved']:
        print("post haas been approved \n")
        return END
    if state['attempt'] >= 3:
        print("reached max attempts")
        return END 
    return "writer"

graph = StateGraph(State)

graph.add_node("writer",writer_node)
graph.add_node("tools",tool_node)
graph.add_node("extract_draft",extract_draft_node)
graph.add_node("reviewer",reviewer_node)

graph.add_edge(START ,"writer")

graph.add_conditional_edges("writer",should_use_tool)

# ReAct loop: tool results go back to the writer, which then writes the post (or searches again)
graph.add_edge("tools","writer")

graph.add_edge("extract_draft","reviewer")

graph.add_conditional_edges("reviewer",should_stop_looping)

app = graph.compile()

topic = input("\nWhat topic do you want a LinkedIn post about?\n> ").strip()

initial_state = {
        "topic": topic,
        "messages": [],
        "draft": "",
        "review_feedback": "",
        "is_approved": False,
        "attempt": 0,
}

final_state = app.invoke(initial_state)
print(final_state["draft"])
print("=" * 55)
print(f"Total attempts: {final_state['attempt']}")
print(f"Approved: {final_state['is_approved']}")