Reflection Agent AI: Self-Improving Tweet Generation with LangGraph

Reflection agent AI explained: a generator writes a tweet, a critic reviews it, and the loop repeats. Built with LangChain, LangGraph and Gemini 2.0 Flash.

Artificial intelligence is developing rapidly. It is critical to design agents that create content, analyze it, and refine it. Enterprises use AI to optimize storage. Consider an AI system that writes a tweet, receives feedback, and refines the output. It repeats this process until specific criteria are met. This mimics the workflow of human content writers. LangChain and LangGraph make this possible. A reflection agent is the part of the system that critiques each tweet the generator writes and sends feedback for the next draft.

This article examines the construction of a self-improving system. The example is an AI Twitter Assistant that generates and improves tweets. A critic agent evaluates the content. This section details the core components and their interactions. It focuses on the design of self-improving AI workflows and the specific function of the reflection agent.

Core Components: LangChain and Generative AI

The system uses LangChain and Google Gemini 2.0 Flash.

The system uses two independent AI roles.

The Generator role creates tweets.

The Reflector role evaluates tweets.

LangChain ChatPromptTemplate defines the system roles and context.

Implementing LangGraph for Stateful Orchestration in the Reflection Agent

LangChain structures individual prompt and LLM call chains. LangGraph extends this capability to stateful, multi-agent applications. LangGraph visualizes application flow as a directed graph. Nodes represent actions or agents. Edges define the transition between nodes.

To see how LangGraph builds a team of agents, read our guide to LangGraph multi-agent systems in LangChain and our overview of agentic frameworks.

The tweet generation system uses two primary nodes:

Generate Node

This node generates initial tweets or retweets based on feedback. It executes the generate_chain. The chain combines the generation_prompt with the LLM.

Reflection

The Reflection Agent node critiques the generated tweet. It applies the reflect_chain using the reflection_prompt and the LLM.

LangGraph tracks the conversation state. As messages exchange and tweets iterate, the state (Sequence[BaseMessage]) propagates between nodes. Each component accesses the full conversation history.

Self-Correction: How the Reflection Agent Drives Iteration

The system’s core mechanism is a self-correction loop. The Reflection Agent initiates this cycle. After the GENERATE node produces a tweet, the process continues. The system enters a reflective state.

How the reflection agent loop works: generate, reflect, revise

1. Generate: The user requests a tweet. The system sends this request to the GENERATE node.

2. Reflect: After generation, the should_continue function checks if the iteration limit is reached. If not, the system proceeds to the REFLECT node. The reflection agent evaluates the tweet as a "viral Twitter influencer." It adds specific feedback to the message history as a HumanMessage.

3. Revise: The system returns to the GENERATE node. The generative agent reviews the previous tweet and the critique. It drafts a new version that addresses the feedback.

The system repeats this cycle until the iteration limit or another termination criterion is met. This iterative self-correction improves output quality and specificity, mirroring human drafting processes.

Stream Output for Enhanced User Experience

Visualize Workflow with Graph Representation

Iterative Refinement via Agent Feedback

The sample tweet in the `if name == "__main__"` block illustrates the value of this self-improvement mechanism. The system accepts a draft tweet for LangChain Tool Calling. The reflection agent evaluates the draft against predefined criteria, such as hook strength, tone, and character limits. It returns specific recommendations. The generation node uses this feedback to produce a revised draft. This process demonstrates the model’s ability to refine output based on structured critique.

This continuous loop allows the agent to refine output against fixed standards. The system iterates on drafts until they meet quality thresholds. This approach improves consistency and precision in content generation.

chains.py
01from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
02from langchain_google_genai import ChatGoogleGenerativeAI
03from dotenv import load_dotenv
04import os
05load_dotenv()
06GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
07reflection_prompt = ChatPromptTemplate.from_messages(
08[
09(
10"system",
11"Grade a tweet for engagement. Provide critique and recommendations for the user's tweet."
12"Provide complete parameters for length, tone, and format,""
13,
14MessagesPlaceholder(variable_name="messages")
15]
16)
17generation_prompt = ChatPromptTemplate.from_messages(
18[
19(
20"system",
21"You are a technical Twitter assistant. Your task is to write high-quality posts."
22"Create the ideal Twitter post for the user's request."
23"If the user provides feedback, return a revised version of your earlier attempt."
24)
25MessagesPlaceholder(variable_name="messages")
26]
27)
28llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=GOOGLE_API_KEY)
29generate_chain = generation_prompt | llm
30reflect_chain = reflection_prompt | llm
main.py
01from typing import List, Sequence
02from dotenv import load_dotenv
03load_dotenv()
04from langchain_core.messages import BaseMessage, HumanMessage
05from langgraph.graph import END, MessageGraph
06from chains import generate_chain, reflect_chain, llm, generation_prompt, reflection_prompt
07REFLECT = "reflect"
08GENERATE = "generate"
09def generation_node(state: Sequence[BaseMessage]):
10# Streaming generation
11print("
12Generation Node Reasoning:", flush=True)
13# Define the prompt manually
14prompt_value = generation_prompt.format_prompt(messages=state)
15for chunk in llm.stream(prompt_value.to_messages()):
16if hasattr(chunk, 'content'):
17print(chunk.content, end="", flush=True)
18print("
19[End of generation]
20", flush=True)
21# Return the complete message
22returning generate_chain.invoke({"messages": state})
23def reflection_node(messages: Sequence[BaseMessage]) -> List[BaseMessage]:
24# Streaming reflection process
25print("
26[Reflection node reasoning]:", flush=True)
27prompt_value = reflection_prompt.format_prompt(messages=messages)
28for chunk in llm.stream (prompt_value.to_messages()):
29if hasattr(chunk, 'content'):
30print(chunk.content, end="", flush=True)
31print("
32[End of reflection]
33", flush=True)
34res = reflect_chain.invoke({"messages": messages})
35return [HumanMessage(content=res.content)]
36builder = MessageGraph()
37builder.add_node(GENERATE, generation_node)
38builder.add_node(REFLECT, reflection_node)
39builder.set_entry_point(GENERATE)
40def should_continue(state: List[BaseMessage]):
41if len(state) > 6:
42return END
43return REFLECT
44builder.add_conditional_edges(GENERATE, should_continue)
45builder.add_edge(REFLECT, GENERATE)
46graph = builder.compile()
47print(graph.get_graph().draw_mermaid())
48graph.get_graph().print_ascii()
49if name == "__main__":
50print("Hello LangGraph")
51inputs = HumanMessage(content="""Improve this tweet:",
52@LangChainAI
53-- The new Tool Calling feature is underused.
54Function calling and agent implementation across models are now simple.
55""")
56response = graph.invoke(inputs)
57for msg in response:
58if hasattr(msg, 'content'):
59print(msg.content)

Graph Visualization & Multi-Agent Workflow

The compiled LangGraph execution graph visualizes the continuous cyclic edge between generate and reflect nodes. The conditional edge evaluates the message state, ensuring that once quality criteria are met or the iteration limit is reached, execution cleanly routes to END.

Reflection Agent Examples: Applications Beyond Tweets

This example demonstrates tweet creation. The core principles apply broadly. A specialized reflection agent can critique and advise other generative AI systems in the following areas:

Blog post composition: An AI writes a paragraph. A content editor agent checks for clarity, brevity, and tone. The writing AI revises the text.

Code generation: An AI produces code. A code reviewer agent checks for bugs, efficiency, and best practices. The coding AI improves the output.

Creative writing: An AI writes a story. A literary critic agent reviews plot, character development, and pacing. The writing AI refines the draft.

Customer service replies: An AI generates a response. A reflection agent evaluates helpfulness and empathy. The AI modifies the message based on this feedback.

Specialized reflection agents enable AI systems to self-correct. These agents combine LLM capabilities with cognitive feedback loops. Frameworks like LangGraph support these loops. The result is AI agents that are proactive, not just reactive.

Conclusion

AI systems are evolving from simple prompt-response models to self-correcting agents. This shift reflects rapid progress in the field. Technologies like LangChain and LangGraph allow developers to build workflows that learn and adjust automatically. The Twitter Techie Influencer Assistant demonstrates this potential. It is one example of what becomes possible when generative AI combines with intelligent orchestration. As these technologies mature, we expect more autonomous systems. These systems will perform complex tasks with high accuracy and continuous refinement.

Read more about AI agents:

View Agentspace

Frequently Asked Questions

Q. 1. What is a reflection agent in AI, and how does it function?

A reflection agent is a specialized AI system that reviews and critiques the output of another AI. In a tweet-writing system, the agent evaluates generated text for style, virality, and length. It provides feedback to the generative AI. The generative AI revises its output based on this feedback. This creates a self-correcting loop.

Q. 2. How does a self-improving AI generate better tweets over time?

Self-improving AI uses iterative feedback loops. The generator creates a draft tweet. The reflection agent critiques the draft. The generator revises the tweet based on the feedback. Repeating this process allows the AI to refine style, tone, and engagement potential. This process produces more polished and effective content.

Q. 3. What tools are used to build a reflection agent for content creation?

This article highlights LangChain and LangGraph as key frameworks. LangChain connects generative AI models with prompts and memory. LangGraph manages multi-agent workflows and conversation state. These frameworks allow developers to orchestrate complex AI systems with iterative improvement.

Q. 4. Can reflection agents be used beyond tweet writing?

Yes. Reflection agents are versatile. They improve blog posts, code generation, creative writing, and customer support responses. They critique and guide AI outputs. Any task that benefits from iterative feedback and refinement can use a reflection agent to achieve higher-quality results.

Q. 5. How can AI service providers like SquareShift help implement reflection agents?

SquareShift designs and deploys self-correcting AI workflows. The team integrates reflection agents into content generation, code review, or customer support systems. This integration ensures the AI continuously improves outputs with minimal manual intervention.

Q. 6. What industries can benefit from SquareShift’s reflection agent solutions?

SquareShift reflection agent solutions serve multiple industries. They support marketing content creation, social media management, software development, creative writing, and customer experience management. Any industry that values automated, high-quality, iterative output can benefit.

Q. 7. Why choose SquareShift for building self-improving AI systems?

SquareShift orchestrates multi-agent AI workflows using frameworks like LangChain and LangGraph. This approach ensures AI systems generate and refine content through iterative reflection. This method helps businesses achieve precise and impactful results.

Q. What is a reflection agent in LangGraph?

In LangGraph, the reflection agent is a node that critiques the tweet the generate node wrote. It runs the reflect chain with the reflection prompt and the LLM, acts as a viral Twitter influencer, and adds its feedback to the message history as a HumanMessage for the next draft.

Q. How does a reflection agent loop stop?

A should_continue function checks whether the iteration limit is reached. If not, the graph goes to the reflect node and then back to the generate node. The loop repeats until the iteration limit or another stop rule is met. Then a conditional edge sends the run to the END node.

Q. Which model does the reflection agent example use?

The example uses LangChain with Google Gemini 2.0 Flash. Gemini 2.0 Flash both generates and evaluates the tweets. LangChain connects the model to prompts and data, ChatPromptTemplate sets the roles, and MessagesPlaceholder keeps the conversation history so the system keeps context across revision requests.

Q. How can you see a reflection agent graph?

LangGraph includes tools to draw the workflow. Compile the graph with builder.compile(), then call graph.get_graph(). The draw_mermaid() function renders a diagram and print_ascii() prints a text map. These views show nodes, edges and data flow, and help developers debug the paths between the generate and reflect nodes.