Runoob Tutorial ArchiveEnglish

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

Three levels of AI capability Layer 1: single-turn QA Q & A User input → LLM → output Example: "Write me a poem" Limitation: single step only Cannot complete complex tasks → Layer 2: Chain invocation Chain Step A → Step B → Step C Example: Translate → summarize → polish Limitation: fixed flow Cannot make dynamic decisions → Layer 3: AI Workflow Includes Agent Agent Perception → planning → tool calling → Reflect → loop iteration Example: research competitors and generate report Dynamic decision-making, can handle open-ended tasks AI Workflow is the main paradigm for deploying AI applications today, and the foundation for building AI Agents

Why AI Workflow is Needed

Limitations of Single Calls

A single LLM call can accomplish very little:

Five core problems solved by AI Workflow

Five Core Problems Solved by AI Workflow Task decomposition Decompose complex tasks Into multiple small steps Focus on one thing per step Write report → research+ Outline + write + review Improve accuracy Reduce per-step pressure Tool integration Call search, database Code executor, API And other external capabilities Search engine, calculator Database, email service Break through knowledge boundaries Connect to the real world Iterative reflection AI can examine itself Output, after finding issues Retry to correct Generate code → run → Error → fix Automatic error correction Quality more assured Parallel processing Multiple subtasks simultaneously Execute without queuing Wait for the previous step to finish Analyze finance simultaneously Three dimensions: technology, market Greatly improve efficiency Save runtime Observability Input and output of each step All can be recorded Monitoring and debugging Logs, tracing Error localization Production-grade reliability Easy to troubleshoot

Core components

A complete AI Workflow is composed of the following core elements.

AI Workflow Core Architecture Components AI Workflow Orchestration engine LLM / Model GPT-4、Claude Gemini, local models The brain of the Workflow Tools Search, code execution Database, external API Interact with the outside Memory Short-term: conversation history Long-term: vector database Cross-session persistence State Task progress, intermediate Results, context passing Like a relay baton Human intervention Review, feedback Correct, authorize Pause high-risk operations Routing / conditional Decide based on conditions Which execution path to take Branch, loop, jump Input / output Text, image, file Structured data All components are orchestrated and coordinated by an orchestration engine (LangChain / LlamaIndex / Dify, etc.)

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.

Pattern 1: Sequential Chain Input User original English article Step 1 Translate English → Chinese GPT-4o Step 2 Summarize Extract core viewpoints Within 100 characters Step 3 Polish Optimize expression Add title Output Refine Chinese summary Includes title and key points The output of each step automatically becomes the input of the next, flowing linearly with clear logic.
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.

Pattern 2: Conditional Routing User issue "How to use Python sorted list?" Intent classification Router Code issues → Code Generation Agent Run code to verify Return results + explanation Knowledge question → RAG knowledge base retrieval Retrieve relevant documents Generate answers based on documents Real-time questions → Web search Search for the latest information Integrate into an answer The routing node dispatches the task to the most suitable processing branch based on the question type.
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.

ai workflow runoob

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.

Pattern 4: ReAct Loop (Reason → Act → Observe → Repeat) Task Query Beijing today Weather and outfit recommendation Thought I need to first obtain Beijing real-time weather Should call the weather API Action Call the weather tool get_weather( city="Beijing") Observation Returns: sunny, temperature 18°C, light breeze (tool execution result) Loop continues reasoning Thought (Round 2) Weather is known, now you can Directly give outfit suggestions Final Answer Beijing is sunny today, 18°C, light jacket recommended. Long pants + sneakers, optionally bring a light jacket as backup. (task complete, exit loop) Each round of "think → act → observe" continuously accumulates information until the LLM deems it ready to produce the final answer.
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."

Pattern 5: Plan & Execute (plan first, then execute) Task objective Research competitors and write Produce analysis report Planner 1 Collect competitor info 2 Extract key features 3 Comparative analysis 4 Write report Execute 1 Search engine Call x3 Execute 2+3 LLM extraction Comparative analysis Execute 4 → output Generate Markdown Competitor analysis report The Planner uses a single LLM call to formulate the global plan, and subsequent steps strictly follow that plan.

Mode Six: Multi-Agent Collaboration

Multiple dedicated Agents collaborate, with each Agent having its own role and set of tools.

Pattern 6: Multi-Agent Collaboration Coordinator Agent Receives the user's task, assigns it to specialized agents, and aggregates the results. Researcher Agent Tools: search engine, web scraping Responsibility: collect materials, organize facts Output: structured information summary ↑ Report to the coordinator Analyst Agent Tools: calculator, Python Responsibility: data analysis, chart generation Output: analysis conclusion ↑ Report to the coordinator Writer Agent Tools: document templates Responsibility: write, polish reports Output: final document ↑ Report to the coordinator Reviewer Agent Tools: fact-checking tool Responsibility: verify accuracy Output: review comments ↑ Report to the coordinator Final deliverable → user Each agent specializes in one skill, the coordinator oversees the whole, and their division of labor far outperforms a single agent.
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.

AI Workflow Mainstream Framework Comparison Framework Locate Core features Suitable for Learning curve Open source LangChain Python/JS Code-first framework Most complete ecosystem Full coverage of Chain, Agent, RAG Most tool integrations (200+) LangSmith Observability Platform Developers with Python basics Requires extensive custom integration Medium √ LangGraph By LangChain Graph-based Agent Framework Stateful workflow Define complex workflows with "graphs" Built-in state management, resumable transfer Supports Human-in-the-Loop Scenarios requiring complex flow control Production-grade agent application Harder √ LlamaIndex Python RAG-specialized framework Strongest at data processing Data ingestion, indexing, retrieval optimized Supports 80+ data source connectors Advanced RAG strategies built-in Knowledge base, document QA scenarios Needs to ingest large amounts of unstructured data Medium √ Dify Open-source LLMOps Visual low-code Full-stack AI platform Build workflows by dragging and dropping, no coding required. Built-in app management, API publishing Supports self-hosting and cloud Non-technical users From rapid prototype to production deployment Minimum √ n8n Automation platform General workflow automation Includes AI nodes 400+ service integrations, visual orchestration AI nodes + traditional automation hybrid Self-hostable, data stays on-premise Needs to connect various SaaS systems Business process automation scenarios Lower √ CrewAI Python Multi-Agent Collaboration Role-playing framework Define Agents by "role" and "task" Built-in delegation and supervision mechanism Minimal API, quick to start Multi-agent collaboration scenarios Beginners with Python basics Lower √ Beginner recommendation: coding background → LangChain / CrewAI; non-technical background → Dify / n8n

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

}

)

print

(

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."

}

)

print

(

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

}

)

print

(

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

(

)

print

(

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)"""

   

print

(

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

)

print

(

"Draft generated, awaiting review:"

)

print

(

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

   

print

(

"Email sent"

)

else

:

   

print

(

"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.

AI Workflow Typical Application Scenarios AI coding assistant User describes need → understand need → Generate code → auto-run → Discover error → auto-fix → Generate documents and test cases Representative: GitHub Copilot Workspace Claude Code、Cursor Automated research report Receive research topic → decompose sub-problems → Parallel collect materials → extract Key info → comprehensive analysis → Generate a complete report with citations Representative: Perplexity Deep Research OpenAI Deep Research Intelligent customer service system Identify user intent → query order Database → retrieve policy documents → Generate personalized reply → Complex issues escalated to humans Representative: AI customer service of major e-commerce platforms Bank intelligent customer service Data analysis automation Upload Excel/CSV → understand Data structure → auto-select Analysis method → execute Python → Generate charts + natural language interpretation Representative: ChatGPT Advanced Data Analysis Content marketing pipeline Input topic and audience → research Hot topic → generate outline → write Full text → SEO optimization → generation Caption description → multi-platform adaptation Representative: various AI writing tools And marketing automation tools Medical assisted diagnosis Patient describes symptoms → structured Medical history → retrieve medical literature → Analyze imaging report → generate Reference suggestion → doctor confirmation Note: high-risk scenarios must be retained Human-in-the-Loop

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

AI Workflow Core Knowledge Points Core elements LLM, tools Memory, state Routing, human Intervene in the six components Form a complete system Six patterns Sequential chain Conditional routing Parallel execution ReAct loop Plan&Execute Multi-Agent Mainstream frameworks LangChain LangGraph LlamaIndex CrewAI Dify / n8n Select on demand Key code Chain invocation tool definition StateGraph (state graph) Agent + Executor Human-in-Loop interrupt_after Key pitfalls Hallucination cascade Infinite loop Context explosion JSON parsing failed Cost overrun Prevention is better than cure Application scenarios AI coding assistant Research report Intelligent customer service Data analysis Content production Medical assistance

Recommended learning path

Phase 1: Understanding the Basics (1 Week)

  1. Understand LLM API calls and be able to make requests using the OpenAI SDK
  2. Run the LangChain sequential chain example in this document
  3. Understand the basic principles of Prompt Engineering

Phase Two: Tools and Agents (2 Weeks)

  1. Learn to define tools using the @tool decorator
  2. Run the ReAct Agent example and observe the verbose logs to understand the loop logic
  3. Build a visual Workflow prototype using Dify or n8n

Phase Three: Complex Workflows (3 Weeks)

  1. Learn LangGraph state graphs to implement workflows with conditional branching
  2. Implement a dual-agent collaborative task using CrewAI
  3. Integrate real tools (Tavily Search, Python REPL)
  4. Observe and debug your Workflow with LangSmith

Phase Four: Production Ready (Ongoing)

  1. Implement error retries and structured output parsing
  2. Cost monitoring and optimization (tiered model usage)
  3. Deploy to production and set up monitoring alerts

Reference Resources