Updated LangGraph reflection agent with max_rounds logic.: update main.py

This commit is contained in:
2026-06-11 16:11:40 +00:00
parent 0c3989827c
commit 906e758e2c
+76 -56
View File
@@ -1,86 +1,105 @@
"""LangGraph reflection agent example.
The agent writes a short answer, critiques it, and rewrites if needed.
""" """
LangGraph Reflection Agent
from typing import TypedDict, Dict Usage:
python main.py "Your question"
"""
import sys import sys
from typing import TypedDict, Dict
from langgraph.graph import StateGraph, END # State definition
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
# Define state
class ReflectState(TypedDict): class ReflectState(TypedDict):
question: str question: str
draft: str draft: str
critique: str critique: str
verdict: str # "ok" | "needs_revision" verdict: str # 'ok' or 'needs_revision'
round: int round: int
max_rounds: int max_rounds: int
# LLM # Node functions
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) async def draft_answer(state: Dict) -> Dict:
from langchain_openai import ChatOpenAI
# Draft node llm = ChatOpenAI(model="gpt-3.5-turbo")
async def draft_answer(state: ReflectState) -> Dict: prompt = f"Write a concise answer (510 sentences) to the following question:\n\n{state['question']}"
prompt = f"Write a short answer (510 sentences) to the following question: {state['question']}" response = await llm.invoke(prompt)
response = await llm.ainvoke(prompt) state["draft"] = response.content
state['draft'] = response.content
return state return state
# Critique node async def reflect(state: Dict) -> Dict:
async def reflect(state: ReflectState) -> Dict: from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo")
prompt = ( prompt = (
f"You are a critic. Evaluate the following draft answer for completeness, specificity, and lack of filler.\n" f"You are a critic evaluating the draft answer for completeness, specificity, and lack of filler.\n"
f"Draft: {state['draft']}\n" f"Draft: {state['draft']}\n"
f"Give a verdict: 'ok' or 'needs_revision'.\n" "Provide verdict (ok or needs_revision) and 23 bullet points of critique."
f"If needs_revision, provide 23 points of critique."
) )
response = await llm.ainvoke(prompt) response = await llm.invoke(prompt)
# Simple parsing: first line verdict, rest critique # Simple parsing
lines = response.content.strip().splitlines() text = response.content.strip()
verdict = lines[0].strip().lower() if "needs_revision" in text.lower():
critique = "\n".join(lines[1:]).strip() state["verdict"] = "needs_revision"
state['verdict'] = verdict else:
state['critique'] = critique state["verdict"] = "ok"
state["critique"] = text
return state return state
# Rewrite node async def rewrite(state: Dict) -> Dict:
async def rewrite(state: ReflectState) -> Dict: from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo")
prompt = ( prompt = (
f"Rewrite the draft answer taking into account the following critique: {state['critique']}\n" f"Rewrite the draft answer incorporating the following critique:\n"
f"Original draft: {state['draft']}" f"Critique: {state['critique']}\n"
"Provide a revised concise answer (510 sentences)."
) )
response = await llm.ainvoke(prompt) response = await llm.invoke(prompt)
state['draft'] = response.content state["draft"] = response.content
state['round'] += 1 state["round"] += 1
return state return state
# Build graph # Build graph
builder = StateGraph(ReflectState) from langgraph.graph import StateGraph
builder.add_node("draft_answer", draft_answer)
builder.add_node("reflect", reflect)
builder.add_node("rewrite", rewrite)
builder.set_entry_point("draft_answer") graph_builder = StateGraph(ReflectState)
builder.add_edge("draft_answer", "reflect")
builder.add_conditional_edges( graph_builder.add_node("draft_answer", draft_answer)
graph_builder.add_node("reflect", reflect)
graph_builder.add_node("rewrite", rewrite)
# Connections
start_edge = "draft_answer"
end_edge = None # will be set in condition
def should_end(state: Dict) -> str:
if state["verdict"] == "ok":
return "END"
if state["round"] >= state.get("max_rounds", 2):
return "END"
return "rewrite"
# Add edges with condition
from langgraph.graph import END
graph_builder.set_entry_point(start_edge)
graph_builder.add_conditional_edges(
"reflect", "reflect",
lambda state: ( should_end,
"END" {
if state["verdict"] == "ok" "rewrite": "rewrite",
or state.get("round", 0) >= state.get("max_rounds", 2) "END": END,
else "rewrite" },
),
) )
builder.add_edge("rewrite", "reflect") # rewrite -> reflect
graph = builder.compile() graph_builder.add_edge("rewrite", "reflect")
graph = graph_builder.compile()
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) < 2: if len(sys.argv) < 2:
print("Usage: python main.py <question>") print("Usage: python main.py \"Your question\"")
sys.exit(1) sys.exit(1)
question = sys.argv[1] question = sys.argv[1]
initial_state: ReflectState = { initial_state: ReflectState = {
@@ -92,6 +111,7 @@ if __name__ == "__main__":
"max_rounds": 2, "max_rounds": 2,
} }
result = graph.invoke(initial_state) result = graph.invoke(initial_state)
print("\nFinal answer:\n", result["draft"]) print("\n--- Final Answer ---")
print("\nCritique:\n", result["critique"]) print(result["draft"])
print("\nVerdict:\n", result["verdict"]) print("\n--- Critique ---")
print(result["critique"])