AI Workflow
AI Workflow
AI Workflow is a system that sequentially combines multiple AI model calls, tool usage, and data processing steps into an automated pipeline.
Calling an LLM once can answer a question, but real-world tasks often require: searching the web → extracting information → analyzing → writing a report → sending an email. AI Workflow strings these steps together, allowing AI to complete the entire task automatically, rather than just answering a single sentence.
An intuitive analogy
Imagine an assembly line:
| Pattern | Analogy | Description |
|---|---|---|
| Single LLM call | Like a craftsman | Give him a piece of iron, and he gives you a sword |
| AI Workflow | Like an entire assembly line | Raw materials go in, automatically go through smelting -> forging -> quenching -> polishing -> packaging, and the finished product comes out |
Each step can be an AI model, a code function, an external API, or a manual review node.
Evolution from Q&A to Action
Why AI Workflow is Needed
Limitations of Single Calls
A single LLM call can accomplish very little:
- Limited context window: cannot read an entire book at once
- Inability to access real-time information: training data has a cutoff date
- Inability to perform actions: cannot actually send emails or run code
- Inability to self-validate: cannot realize and correct errors after generation
- Complex tasks are prone to errors: doing too many things in one step leads to decreased quality
Five core problems solved by AI Workflow
Core components
A complete AI Workflow is composed of the following core elements.
Detailed explanation of each element
LLM (Large Language Model) - the "brain" of the Workflow, responsible for reasoning, generation, and decision-making. Commonly used: GPT-4o, Claude 3.5, Gemini 1.5, local Llama 3.
Tools - interfaces that allow AI to interact with the external world, including: search engines (Tavily, Serper, Bing), code executors (Python REPL, sandbox environment), database queries (SQL, vector DB), external APIs (weather, stock, email, calendar), and file operations (read/write, PDF/Excel parsing).
Memory - short-term memory stores the current conversation history (present in the prompt), long-term memory achieves cross-session persistent storage via vector databases + RAG, and working memory maintains intermediate states during task execution.
State - A carrier of information passed between steps, like a baton, where each step can read the previous step's result and write a new result.
Router/Condition - Dynamically determines the next step based on the previous step's output, implementing complex flow control such as branching, looping, and jumping.
Human in the Loop - Pauses at critical nodes to wait for human confirmation, suitable for high-risk operations (such as deleting data, sending emails, or financial operations).
Six Common Workflow Patterns
The following are the six most commonly used design patterns in AI Workflows, ranging from simple to complex, suitable for different scenarios.
Pattern One: Sequential Chain
The most basic pattern, where steps A → B → C execute linearly, and the output of the previous step is the input for the next step.
| Dimension | Description |
|---|---|
| Applicable Scenarios | Document processing pipeline, content generation, data transformation |
| Advantages | Simple, predictable |
| Disadvantages | Rigid, cannot dynamically adjust based on content |
Mode Two: Conditional Routing
Dynamically select different subsequent paths based on the output content of a certain step.
| Dimension | Description |
|---|---|
| Applicable scenarios | Intelligent customer service, multi-functional assistant, question classification processing |
| Advantages | Flexible, high resource utilization |
| Disadvantages | Routing logic needs careful design; classification errors affect the entire process. |
Mode Three: Parallel Execution
Multiple subtasks run concurrently, and the results are aggregated at the end.

| Dimension | Description |
|---|---|
| Applicable Scenarios | Multi-dimensional analysis, batch processing, independent subtasks |
| Advantages | Significant speed improvement |
| Disadvantages | Requires handling concurrency control and result merging logic |
Mode Four: ReAct Loop (Reason + Act)
The AI first reasons to decide what to do, then acts by calling tools, and continues reasoning based on the results until the task is complete. This is the core pattern of an AI Agent.
| Dimension | Description |
|---|---|
| Applicable scenarios | AI Agent, complex task execution, open-ended problem solving |
| Advantages | Dynamic and flexible, capable of handling unknown situations |
| Disadvantages | The number of iterations is uncontrollable, a maximum step count needs to be set to prevent infinite loops |
Mode Five: Plan & Execute
First let the LLM formulate a complete plan, then execute it step by step according to the plan. The difference from ReAct is "think clearly first, then act."
Mode Six: Multi-Agent Collaboration
Multiple dedicated Agents collaborate, with each Agent having its own role and set of tools.
| Dimension | Description |
|---|---|
| Applicable Scenarios | Complex software development, scientific research assistance, enterprise automation |
| Advantages | Dedicated specialization, higher quality, easy to scale |
| Disadvantages | The system complexity is high, and inter-Agent communication requires careful design |
Comparison of mainstream frameworks and tools
The following is a panoramic comparison of the most mainstream AI Workflow frameworks, to help you make a choice based on your own situation.
Framework selection decision tree
Based on your specific situation, choose a suitable framework according to the following decision tree:
Original prompt (Chinese, left untranslated)
你的情况是什么?
│
├─── 没有编程基础,想用可视化工具搭建
│ ├─── 主要是 AI 应用(问答、生成)→ Dify(首选)
│ └─── 需要连接 Slack/邮件等 SaaS 系统 → n8n
│
├─── 有 Python 基础,代码优先
│ ├─── 做知识库 / RAG 系统 → LlamaIndex
│ ├─── 做多 Agent 协作,想快速上手 → CrewAI
│ ├─── 需要复杂有状态流程控制 → LangGraph
│ └─── 通用场景,想要最大生态 → LangChain
│
└─── 已有明确场景,生产级要求
├─── 高并发、精细控制 → LangGraph + LangSmith
└─── 企业部署、私有化 → Dify 自托管
Quick start: Python code examples
The following examples demonstrate the implementation of AI Workflow step-by-step, from the simplest sequential chain to complex multi-Agent collaboration.
LangChain sequential chain
The most basic Workflow mode, which chains multiple LLM call steps using the pipe operator |.
Install dependencies:
pip install langchain langchain-openai
Instance
from
langchain_openai
import
ChatOpenAI
from
langchain_core.
prompts
import
ChatPromptTemplate
from
langchain_core.
output_parsers
import
StrOutputParser
llm
=
ChatOpenAI
(
model
=
"gpt-4o-mini"
,
api_key
=
"your-api-key"
)
─── Define three steps ────────────────────────────────────────────
Step 1: Translate the article into Chinese
translate_prompt
=
ChatPromptTemplate.
from_template
(
"Translate the following English article into Chinese while preserving the original meaning:\n\n{article}"
)
Step 2: Extract summary
summarize_prompt
=
ChatPromptTemplate.
from_template
(
"Please extract the following article into 3 key points, one sentence per point:\n\n{translated}"
)
Step 3: Generate Title
title_prompt
=
ChatPromptTemplate.
from_template
(
"Based on the following summary, generate an attractive Chinese title (within 15 characters): \n\n{summary}"
)
parser
=
StrOutputParser
(
)
─── Link into a pipeline using the | operator ─────────────────────────────────
chain
=
(
{
"translated"
: translate_prompt | llm |
parser
}
|
{
"summary"
: summarize_prompt | llm |
parser
,
"translated"
:
lambda
x: x
[
"translated"
]
}
| title_prompt | llm |
parser
)
─── Run ────────────────────────────────────────────────────
article
=
"""
Artificial intelligence is transforming how we work and live.
From automating repetitive tasks to assisting in creative work,
AI tools are becoming indispensable in modern workflows...
"""
result
=
chain.
invoke
(
{
"article"
: article
}
)
(
result
)
Original prompt (Chinese, left untranslated)
AI 正在重塑现代工作流:从自动化到创意辅助
Tool Calling Agent (ReAct Mode)
ReAct is the core pattern for AI Agents, allowing the AI to cycle between thinking and acting until the task is completed.
Example
from
langchain_openai
import
ChatOpenAI
from
langchain.
agents
import
AgentExecutor
,
create_react_agent
from
langchain_core.
tools
import
tool
from
langchain
import
hub
import
requests
,
datetime
─── Define tools ────────────────────────────────────────────────
@
tool
def
get_weather
(
city:
str
)
str
:
"""Get the current weather information for a specified city"""
Replace with a real weather API in actual projects
mock_data
=
{
"Beijing"
:
"Sunny, 22°C, light breeze"
,
"Shanghai"
:
"Cloudy, 26°C, 75% humidity"
,
"Guangzhou"
:
"Light rain, temperature 30°C, recommend bringing an umbrella"
,
}
return
mock_data.
get
(
city
,
f
"No weather data for {city}"
)
@
tool
def
search_web
(
query:
str
)
str
:
"""Searches for information on the web and returns a summary of the relevant content"""
Integrate Tavily / Serper API in actual projects
return
f
Search results for '{query}': This is a simulated search result...
@
tool
def
calculate
(
expression:
str
)
str
:
"""Calculates a mathematical expression, for example '2 + 3 * 4'"""
try
:
result
=
eval
(
expression
,
{
"builtins"
:
{
}
}
,
{
}
)
return
str
(
result
)
except
Exception
as
e:
return
f
"Calculation error: {e}"
@
tool
def
get_date
(
)
str
:
"""Get today's date"""
return
datetime
.
date
.
today
(
)
.
strftime
(
"YYYY-MM-DD"
)
─── Create Agent ───────────────────────────────────────────────
tools
=
[
get_weather
,
search_web
,
calculate
,
get_date
]
llm
=
ChatOpenAI
(
model
=
"gpt-4o"
,
temperature
=
0
)
Use the standard ReAct prompt from LangChain Hub
prompt
=
hub.
pull
(
"hwchase17/react"
)
agent
=
create_react_agent
(
llm
,
tools
,
prompt
)
agent_executor
=
AgentExecutor
(
agent
=
agent
,
tools
=
tools
,
verbose
=
True
,
Print the thought process for each step for debugging convenience
max_iterations
=
8
,
Prevent infinite loops
handle_parsing_errors
=
True
)
─── Run ────────────────────────────────────────────────────
result
=
agent_executor.
invoke
(
{
"input"
:
"What is today's date? What is the weather like in Beijing? If walking 5km consumes about 300 calories,"
"running the same distance consumes about 1.6 times more than walking. Please calculate the calories burned while running."
}
)
(
result
[
"output"
]
)
The Agent will automatically decide: first call get_date → get_weather("Beijing") → calculate("300*1.6")
Finally, it will synthesize all the information to provide a complete answer
LangGraph State Workflow
LangGraph defines complex workflows using a graph, where each node is a function and edges define the transition logic.
Example
from
langgraph.
graph
import
StateGraph
,
END
from
langchain_openai
import
ChatOpenAI
from
typing
import
TypedDict
,
Annotated
import
operator
─── Define state structure (data passed between nodes) ────────────────────────
class
ResearchState
(
TypedDict
)
:
topic:
str
Research topic
research_notes:
str
Research notes
draft:
str
Draft
review_feedback:
str
Review feedback
final_report:
str
Final report
revision_count: Annotated
[
int
,
operator
.
add
]
Number of modifications (cumulative)
llm
=
ChatOpenAI
(
model
=
"gpt-4o"
)
─── Define node function ─────────────────────────────────────────────
def
research_node
(
state: ResearchState
)
dict
:
"""Node 1: Research Phase"""
response
=
llm.
invoke
(
f
"Please conduct a brief survey on the following topic and list 5 key points: {state['topic']}"
)
return
{
"research_notes"
: response.
content
}
def
write_node
(
state: ResearchState
)
dict
:
"""Node 2: Draft Writing"""
prompt
=
f
"""
Topic: {state['topic']}
Research notes: {state['research_notes']}
{'Last review feedback: ' + state.get('review_feedback', '') if state.get('review_feedback') else ''}
Please write a draft analysis report of about 300 words based on the above content.
"""
response
=
llm.
invoke
(
prompt
)
return
{
"draft"
: response.
content
,
"revision_count"
:
1
}
def
review_node
(
state: ResearchState
)
dict
:
Node 3: Review Draft
response
=
llm.
invoke
(
f
"Review the following report. Reply with 'APPROVED' if the quality meets the standard, otherwise provide specific revision suggestions: {state['draft']}"
)
return
{
"review_feedback"
: response.
content
}
def
finalize_node
(
state: ResearchState
)
dict
:
"""Node 4: Final Draft"""
return
{
"final_report"
: state
[
"draft"
]
}
─── Routing function: determines the path after review ─────────────────────────────
def
should_revise
(
state: ResearchState
)
str
:
if
"APPROVED"
in
state
[
"review_feedback"
]
:
return
"finalize"
→ Final draft
elif
state
[
"revision_count"
]
=
3
:
return
"finalize"
→ Force end after more than 3 modifications
else
:
return
"revise"
→ Return writing node revision
─── Build workflow graph ─────────────────────────────────────────────
workflow
=
StateGraph
(
ResearchState
)
Add node
workflow.
add_node
(
"research"
,
research_node
)
workflow.
add_node
(
"write"
,
write_node
)
workflow.
add_node
(
"review"
,
review_node
)
workflow.
add_node
(
"finalize"
,
finalize_node
)
Set entry point
workflow.
set_entry_point
(
"research"
)
Add edge (define flow logic)
workflow.
add_edge
(
"research"
,
"write"
)
Research -> Write
workflow.
add_edge
(
"write"
,
"review"
)
Writing -> Review
Conditional edge: Choose a path based on the result after review
workflow.
add_conditional_edges
(
"review"
,
should_revise
,
{
"revise"
:
"write"
,
Need to revise -> Go back to writing
"finalize"
:
"finalize"
Approved → Finalized
}
)
workflow.
add_edge
(
"finalize"
,
END
)
Compile and run
app
=
workflow.
compile
(
)
result
=
app.
invoke
(
{
"topic"
:
"The Impact of Generative AI on the Software Development Industry"
,
"revision_count"
:
0
}
)
(
result
[
"final_report"
]
)
CrewAI Multi-Agent Collaboration
CrewAI allows multiple Agents to collaborate like a team by defining roles and tasks.
Example
from
crewai
import
Agent
,
Task
,
Crew
,
Process
from
langchain_openai
import
ChatOpenAI
llm
=
ChatOpenAI
(
model
=
"gpt-4o"
)
─── Define Agent (Role) ────────────────────────────────────────
researcher
=
Agent
(
role
=
"Market Researcher"
,
goal
=
"Collect and organize comprehensive and accurate market information about the target topic"
,
backstory
=
"You are an experienced market analyst skilled at extracting key insights from massive amounts of information"
,
llm
=
llm
,
verbose
=
True
)
analyst
=
Agent
(
role
=
"Data Analyst"
,
goal
=
Based on information provided by the researcher, conduct in-depth analysis and draw valuable conclusions
,
backstory
=
You are skilled at speaking with data and can discover trends and opportunities hidden behind the information
,
llm
=
llm
,
verbose
=
True
)
writer
=
Agent
(
role
=
"Report Writing Expert"
,
goal
=
"Write the analysis conclusions into a clear, professional, and persuasive report"
,
backstory
=
"You have extensive business writing experience and can make complex analyses easy to understand"
,
llm
=
llm
,
verbose
=
True
)
─── Define Task ────────────────────────────────────────
research_task
=
Task
(
description
=
"Research the current status of the new energy vehicle market in China, including major brands, market share, and growth trends"
,
expected_output
=
"A market research report containing 5 key data points, including numbers and specific facts"
,
agent
=
researcher
)
analysis_task
=
Task
(
description
=
"Analyze opportunities and risks for the next 3 years based on the research report and provide investment rating recommendations"
,
expected_output
=
"SWOT Analysis Table + Investment Rating (Strong Buy/Buy/Neutral/Hold) + Reasons"
,
agent
=
analyst
,
context
=
[
research_task
]
Output of the dependency research task
)
writing_task
=
Task
(
description
=
"Integrate the research and analysis into a professional investment brief of 500 words with clear formatting"
,
expected_output
=
"A briefing paper containing four sections: executive summary, market status, opportunities and risks, and investment recommendations"
,
agent
=
writer
,
context
=
[
research_task
,
analysis_task
]
)
─── Build a team and execute ───────────────────────────────────────────
crew
=
Crew
(
agents
=
[
researcher
,
analyst
,
writer
]
,
tasks
=
[
research_task
,
analysis_task
,
writing_task
]
,
process
=
Process.
sequential
,
Sequential execution (can also be changed to hierarchical)
verbose
=
True
)
result
=
crew.
kickoff
(
)
(
result
)
Human-in-the-Loop (manual review node)
LangGraph supports pausing at critical steps and continuing execution after manual confirmation.
Instance
from
langgraph.
graph
import
StateGraph
,
END
from
langgraph.
checkpoint
.
memory
import
MemorySaver
from
typing
import
TypedDict
class
EmailState
(
TypedDict
)
:
recipient:
str
content:
str
approved:
bool
def
draft_email
(
state: EmailState
)
dict
:
"""Draft email"""
content
=
f
"Dear {state['recipient']},\n\nThis email content was drafted by AI...\n\nSincerely"
return
{
"content"
: content
}
def
send_email
(
state: EmailState
)
dict
:
"""Send email (high-risk operation, requires manual review before execution)"""
(
f
"Email has been sent to {state['recipient']}"
)
return
{
}
Routing: Decide whether to send based on manual review results
def
check_approval
(
state: EmailState
)
str
:
return
"send"
if
state.
get
(
"approved"
)
else
END
workflow
=
StateGraph
(
EmailState
)
workflow.
add_node
(
"draft"
,
draft_email
)
workflow.
add_node
(
"send"
,
send_email
)
workflow.
set_entry_point
(
"draft"
)
pause after draft completion, wait for manual review (interrupt_after)
workflow.
add_conditional_edges
(
"draft"
,
check_approval
,
{
"send"
:
"send"
,
END: END
}
)
workflow.
add_edge
(
"send"
,
END
)
Use MemorySaver to support interruption and recovery
memory
=
MemorySaver
(
)
app
=
workflow.
compile
(
checkpointer
=
memory
,
interrupt_after
=
[
"draft"
]
Pause after the draft node
)
config
=
{
"configurable"
:
{
"thread_id"
:
"email-001"
}
}
First run: pauses after reaching draft
state
=
app.
invoke
(
{
"recipient"
:
"Customer A"
,
"approved"
:
False
}
,
config
)
(
"Draft generated, awaiting review:"
)
(
state
[
"content"
]
)
Update the status and continue execution after manual review
user_input
=
input
(
"\nApprove sending? (y/n): "
)
if
user_input.
lower
(
)
==
"y"
:
app.
update_state
(
config
,
{
"approved"
:
True
}
)
app.
invoke
(
None
,
config
)
Continue from breakpoint
(
"Email sent"
)
else
:
(
"Sending canceled"
)
Prompt Engineering: Key Techniques in Workflows
In AI Workflows, the quality of the prompt directly affects the output quality of each node.
Instance
Vague role definition
system_prompt = "You are an AI assistant to help me analyze this document"
Clear role definition (recommended)
system_prompt
=
"""
You are a professional financial analyst specializing in identifying risk signals in financial reports.
Your task: Extract all key data points related to liabilities, cash flow, and profitability from the following report.
Output format: JSON, containing risk_level (high/medium/low) and key_findings (list).
Note: Output only JSON, do not add any explanatory text.
"""
Example
Pass unstructured text
state["previous_output"] = "Analysis result: This company looks good, with some risks..."
Pass structured data (recommended)
state
[
"analysis_result"
]
=
{
"risk_level"
:
"medium"
,
"key_findings"
:
[
"Debt ratio 45%, industry average 38%"
,
"Cash flow is positive, Q3 is down 12% quarter-over-quarter"
]
,
"recommendation"
:
"Hold cautiously"
}
Instance
Force JSON output in the prompt
prompt
=
"""
Please analyze the sentiment of the following text.
Strictly output in the following JSON format, do not add any other content:
{
"sentiment": "positive" | "negative" | "neutral",
"confidence": 0.0-1.0,
"reason": "Brief description"
}
Text: {text}
"""
Error handling and retry
Instance
from
tenacity
import
retry
,
stop_after_attempt
,
wait_exponential
import
logging
@
retry
(
stop
=
stop_after_attempt
(
3
)
,
Maximum 3 retries
wait
=
wait_exponential
(
multiplier
=
1
,
min
=
2
,
max
=
10
)
Exponential backoff wait
)
def
call_llm_with_retry
(
prompt:
str
)
str
:
try
:
response
=
llm.
invoke
(
prompt
)
return
response.
content
except
Exception
as
e:
logging
.
error
(
f
"LLM call failed: {e}"
)
raise
def
safe_parse_json
(
text:
str
)
dict
:
"Safely parse LLM output JSON"
import
json
,
re
Extract the JSON part (LLM sometimes adds extra descriptive text)
json_match
=
re
.
search
(
r
'{.*}'
,
text
,
re
.
DOTALL
)
if
json_match:
try
:
return
json.
loads
(
json_match.
group
(
)
)
except
json.
JSONDecodeError
:
pass
return
{
"error"
:
"Parsing failed"
,
"raw"
: text
}
Cost Control
Instance
─── Select Model Based on Task Importance ────────────────────────────────
def
get_llm
(
task_type:
str
)
:
if
task_type
==
"classification"
:
Classification tasks, lightweight models are sufficient
return
ChatOpenAI
(
model
=
"gpt-4o-mini"
)
elif
task_type
==
"generation"
:
Generation task, use medium model
return
ChatOpenAI
(
model
=
"gpt-4o-mini"
)
elif
task_type
==
"reasoning"
:
Complex reasoning, use a strong model
return
ChatOpenAI
(
model
=
"gpt-4o"
)
─── Cache repeated requests ──────────────────────────────────────────
from
langchain.
globals
import
set_llm_cache
from
langchain_community.
cache
import
InMemoryCache
set_llm_cache
(
InMemoryCache
(
)
)
Identical inputs are returned directly from the cache, avoiding duplicate billing
─── Text chunking to avoid overly long content ──────────────────────────────────────
from
langchain.
text_splitter
import
RecursiveCharacterTextSplitter
splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
2000
,
2000 characters per chunk
chunk_overlap
=
200
Overlap of 200 characters ensures context coherence
)
chunks
=
splitter.
split_text
(
long_document
)
Typical application scenarios
AI Workflow has been widely implemented in various fields, and here are six representative scenarios.
Best Practices and Common Pitfalls
Common Pitfalls and Solutions
These are the most common problems beginners encounter when using AI Workflow.
| Pitfall | Phenomenon | Solution |
|---|---|---|
| Hallucination Cascade | Previous AI output error is passed as fact to the next step, amplifying the error | Add verification steps at critical nodes; use tools to obtain numerical information |
| Infinite loop | ReAct Agent repeatedly calls tools without knowing when to stop | Set max_iterations; provide clear termination conditions to the LLM |
| Context explosion | As steps increase, the text passed to the LLM gets longer and exceeds the window | Pass only necessary fields in each step; use summarization to compress historical information |
| Tool misuse | Agent repeatedly calls tools when it could answer directly | Optimize tool descriptions; clearly instruct the LLM when tools are not needed |
| JSON parsing failed | LLM output format is unstable, causing program crash | Add safe_parse_json; use LangChain OutputParser |
| Cost overrun | Token usage was not estimated, leading to higher than expected end-of-month bill | First test with gpt-4o-mini; monitor usage with LangSmith |
| Concurrent conflicts | Multiple Agents writing to the same state simultaneously causing data corruption | Use LangGraph's built-in state management; avoid sharing mutable state |
Summary and learning path
Review of core knowledge points
Recommended learning path
Phase 1: Understanding the Basics (1 Week)
- Understand LLM API calls and be able to make requests using the OpenAI SDK
- Run the LangChain sequential chain example in this document
- Understand the basic principles of Prompt Engineering
Phase Two: Tools and Agents (2 Weeks)
- Learn to define tools using the @tool decorator
- Run the ReAct Agent example and observe the verbose logs to understand the loop logic
- Build a visual Workflow prototype using Dify or n8n
Phase Three: Complex Workflows (3 Weeks)
- Learn LangGraph state graphs to implement workflows with conditional branching
- Implement a dual-agent collaborative task using CrewAI
- Integrate real tools (Tavily Search, Python REPL)
- Observe and debug your Workflow with LangSmith
Phase Four: Production Ready (Ongoing)
- Implement error retries and structured output parsing
- Cost monitoring and optimization (tiered model usage)
- Deploy to production and set up monitoring alerts