Ai Workflow
AI Workflow (AI Workflow) | Rookie Tutorial\\n\\nAI Workflow (AI Workflow) is a system that orderly combines multiple AI model calls, tool usage, and data processing steps into an automated pipeline.\\n\\nA single LLM call can answer questions, but real-world tasks often require: search web pages β extract information β analyze β write reports β send emails. AI Workflow strings these steps together, allowing AI to automatically complete entire tasks, rather than just answering a single sentence.\\n\\n### An Intuitive Analogy\\n\\nImagine an assembly line:\\n\\n| Pattern | Analogy | Description |\\n| --- | --- | --- |\\n| Single LLM call | Like a craftsman | Give him a piece of iron, he returns you a sword |\\n| AI Workflow | Like the entire production line | Raw materials go in, automatically go through smelting β forging β quenching β grinding β packaging, finished product comes out |\\n\\nEach step can be an AI model, code function, external API, or human review node.\\n\\n### Evolution from Q&A to Getting Things Done\\n\\n* * *\\n\\n## Why AI Workflow is Needed\\n\\n### Limitations of Single Calls\\n\\nWhat a single LLM call can accomplish is very limited:\\n\\n* Limited context window: Cannot read an entire book at once\\n* Cannot access real-time information: Training data has a cutoff date\\n* Cannot execute actions: Cannot actually send emails, write code and run it\\n* Cannot self-verify: Cannot recognize and correct errors after generating them\\n* Complex tasks are prone to errors: Doing too many things in one step leads to quality degradation\\n\\n### Five Core Problems Solved by AI Workflow\\n\\n* * *\\n\\n## Core Components\\n\\nA complete AI Workflow consists of the following core elements.\\n\\n### Detailed Explanation of Each Element\\n\\nLLM (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.\\n\\nTools - Interfaces that allow AI to interact with the external world, including: search engines (Tavily, Serper, Bing), code executors (Python REPL, sandbox environments), database queries (SQL, vector DB), external APIs (weather, stocks, email, calendar), file operations (read/write, parse PDF/Excel).\\n\\nMemory - Short-term memory stores current session conversation history (stored in prompt), long-term memory achieves cross-session persistent storage through vector database + RAG, working memory maintains intermediate state during task execution.\\n\\nState - The information carrier passed between tasks at each step, like a relay baton, where each step can read the previous step's results and write new results.\\n\\nRouter/Conditions - Dynamically determine the next step based on the previous step's output, enabling complex flow control such as branching, looping, and jumping.\\n\\nHuman in the Loop - Pause at critical nodes to wait for human confirmation, suitable for high-risk operations (such as deleting data, sending emails, financial operations).\\n\\n* * *\\n\\n## Six Common Workflow Patterns\\n\\nThe following are the six most commonly used design patterns in AI Workflow, from simple to complex, applicable to different scenarios.\\n\\n### Pattern 1: Sequential Chain\\n\\nThe most basic pattern, steps A β B β C execute linearly, with the previous step's output being the next step's input.\\n\\n| Dimension | Description |\\n| --- | --- |\\n| Applicable scenarios | Document processing pipeline, content generation, data transformation |\\n| Advantages | Simple, predictable |\\n| Disadvantages | Rigid, cannot dynamically adjust based on content |\\n\\n### Pattern 2: Conditional Routing\\n\\nDynamically select different subsequent paths based on the output content of a certain step.\\n\\n| Dimension | Description |\\n| --- | --- |\\n| Applicable scenarios | Intelligent customer service, multi-functional assistants, problem classification and processing |\\n| Advantages | Flexible, high resource utilization |\\n| Disadvantages | Routing logic requires careful design, classification errors affect the entire process |\\n\\n### Pattern 3: Parallel Execution\\n\\nMultiple subtasks run simultaneously, with results aggregated at the end.\\n\\n!(#)\\n\\n| Dimension | Description |\\n| --- | --- |\\n| Applicable scenarios | Multi-dimensional analysis, batch processing, independent subtasks |\\n| Advantages | Significant speed improvement |\\n| Disadvantages | Requires handling concurrency control and result merging logic |\\n\\n### Pattern 4: ReAct Loop (Reason + Act)\\n\\nAI first reasons to decide what to do, then acts by calling tools, and continues reasoning based on results, cycling until the task is completed. This is the core pattern of AI Agent.\\n\\n| Dimension | Description |\\n| --- | --- |\\n| Applicable scenarios | AI Agent, complex task execution, open-ended problem solving |\\n| Advantages | Dynamic and flexible, can handle unknown situations |\\n| Disadvantages | Loop iterations are uncontrollable, need to set maximum steps to prevent infinite loops |\\n\\n### Pattern 5: Plan & Execute (Plan then Execute)\\n\\nFirst let LLM formulate a complete plan, then execute step by step according to the plan. The difference from ReAct is "think clearly first, then act".\\n\\n### Pattern 6: Multi-Agent\\n\\nMultiple specialized Agents collaborate, with each Agent having its own role and toolset.\\n\\n| Dimension | Description |\\n| --- | --- |\\n| Applicable scenarios | Complex software development, scientific research assistance, enterprise automation |\\n| Advantages | Specialized and dedicated, higher quality, easy to extend |\\n| Disadvantages | High system complexity, Agent communication requires careful design |\\n\\n* * *\\n\\n## Comparison of Mainstream Frameworks and Tools\\n\\nThe following is a comprehensive comparison of the most mainstream AI Workflow frameworks currently, to help you make choices based on your situation.\\n\\n### Framework Selection Decision Tree\\n\\nBased on your specific situation, follow the decision tree below to choose the appropriate framework:\\n\\nWhat is your situation?βββββ No programming foundation, want to build with visual toolsβ ββββ Mainly AI applications (Q&A, generation) β Dify (first choice)β ββββ Need to connect Slack/email and other SaaS systems β n8n βββββ Have Python foundation, code-firstβ ββββ Building knowledge base / RAG system β LlamaIndexβ ββββ Building multi-Agent collaboration, want to get started quickly β CrewAIβ ββββ Need complex stateful flow control β LangGraphβ ββββ General scenarios, want the largest ecosystem β LangChainβββββ Have clear scenarios, production-level requirements ββββ High concurrency, fine-grained control β LangGraph + LangSmith ββββ Enterprise deployment, privatization β Dify self-hosted\\n\\n* * *\\n\\n## Quick Start: Python Code Examples\\n\\nThe following examples demonstrate AI Workflow implementation methods from the simplest sequential chain to complex multi-Agent collaboration.\\n\\n### LangChain Sequential Chain\\n\\nThe most basic Workflow pattern, using the pipe operator | to chain multiple LLM call steps.\\n\\nInstall dependencies:\\n\\npip install langchain langchain-openai\\n\\n## Example\\n\\nfrom langchain_openai import ChatOpenAI\\n\\nfrom langchain_core.prompts import ChatPromptTemplate\\n\\nfrom langchain_core.output_parsers import StrOutputParser\\n\\nllm = ChatOpenAI(model="gpt-4o-mini", api_key="your-api-key")\\n\\n# βββ Define three steps ββββββββββββββββββββββββββββββββββββββββββββ\\n\\n# Step 1: Translate article to 1. Please distill the following article into 3 key points, one sentence each: nn\\n\\n translate_prompt = ChatPromptTemplate.from_template(\\n\\n"Translate the following English article into Chinese, keeping the original meaning: nn{article}"\\n\\n)\\n\\n# Step 2: Extract summary\\n\\n summarize_prompt = ChatPromptTemplate.from_template(\\n\\n"Please distill the following article into 3 key points, one sentence each: nn{translated}"\\n\\n)\\n\\n# Step 3: Generate title\\n\\n title_prompt = ChatPromptTemplate.from_template(\\n\\n"Based on the following summary, generate an engaging Chinese title (within 15 characters): nn{summary}"\\n\\n)\\n\\nparser= StrOutputParser()\\n\\n# βββ Link into pipeline with | operator βββββββββββββββββββββββββββββββββ\\n\\n chain =(\\n\\n{"translated": translate_prompt | llm | parser}\\n\\n | {"summary": summarize_prompt | llm | parser,\\n\\n"translated": lambda x: x}\\n\\n | title_prompt | llm | parser\\n\\n)\\n\\n# βββ Run ββββββββββββββββββββββββββββββββββββββββββββββββββββ\\n\\n article ="""\\n\\n Artificial intelligence is transforming how we work and live.\\n\\n From automating repetitive tasks to assisting in creative work,\\n\\n AI tools are becoming indispensable in modern workflows...\\n\\n """\\n\\nresult = chain.invoke({"article": article})\\n\\nprint(result)\\n\\nAI Reshaping modern workflows: from automation to creative assistance\\n### Tool-Calling Agent (ReAct Pattern)\\n\\nReAct is the core pattern of AI Agent, allowing AI to cycle between thinking and acting until the task is completed.\\n\\n## Example\\n\\nfrom langchain_openai import ChatOpenAI\\n\\nfrom langchain.agents import AgentExecutor, create_react_agent\\n\\nfrom langchain_core.tools import tool\\n\\nfrom langchain import hub\\n\\nimport requests,datetime\\n\\n# βββ Define tools ββββββββββββββββββββββββββββββββββββββββββββββββ\\n\\n@tool\\n\\ndef get_weather(city: str) ->str:\\n\\n"""Fetch current weather information for the specified city"""\\n\\n# Replace with a real weather API in actual projects\\n\\n mock_data ={\\n\\n"Beijing": "Sunny, temperature 22Β°CοΌLight breeze",\\n\\n"Shanghai": "Cloudy, temperature 26Β°CοΌHumidity 75%",\\n\\n"Guangzhou": "Light rain, temperature 30Β°CοΌUmbrella recommended",\\n\\n}\\n\\nreturn mock_data.get(city, f"N/A {city} 's weather data")\\n\\n@tool\\n\\ndef search_web(query: str) ->str:\\n\\n"""Search for information on the web and return a summary of relevant content"""\\n\\n# Integrate Tavily / Serper API in actual projects\\n\\nreturn f"Search '{query}' Result: This is a simulated Search result..."\\n\\n@tool\\n\\ndef calculate(expression: str) ->str:\\n\\n"""Evaluate mathematical expressions, e.g., '2 + 3 * 4'"""\\n\\ntry:\\n\\n result =eval(expression,{"__builtins__": {}},{})\\n\\nreturn str(result)\\n\\nexcept Exception as e:\\n\\nreturn f"Calculation error:{e}"\\n\\n@tool\\n\\ndef get_date() ->str:\\n\\n"""Get Today's Date"""\\n\\nreturn datetime.date.today().strftime("%YYear%mMonth%dDay")\\n\\n# βββ Create Agent βββββββββββββββββββββββββββββββββββββββββββββββ\\n\\n tools =[get_weather, search_web, calculate, get_date]\\n\\n llm = ChatOpenAI(model="gpt-4o", temperature=0)\\n\\n# Use the standard ReAct prompt from LangChain Hub\\n\\n prompt = hub.pull("hwchase17/react")\\n\\nagent = create_react_agent(llm, tools, prompt)\\n\\n agent_executor = AgentExecutor(\\n\\n agent=agent,\\n\\n tools=tools,\\n\\n verbose=True,# Print the thinking process for each step to facilitate debugging\\n\\n max_iterations=8,# Prevent infinite loops\\n\\n handle_parsing_errors=True\\n\\n)\\n\\n# βββ Run ββββββββββββββββββββββββββββββββββββββββββββββββββββ\\n\\n result = agent_executor.invoke({\\n\\n"input": "What's the date today? What's the weather like in Beijing? If walking 5km outdoors burns about 300 calories,"\\n\\n"Running the same distance burns approximately 1.6 times, please calculate the calories burned by running."\\n\\n})\\n\\nprint(result)\\n\\n# Agent Will automatically decide: first call get_date β get_weather("Beijing") β calculate("300*1.6")\\n\\n# Finally, synthesize all information to provide a complete answer\\n\\n### LangGraph Stateful Workflow\\n\\nLangGraph defines complex flows using graphs, where each node is a function and edges define transition logic.\\n\\n## Example\\n\\nfrom langgraph.graph import StateGraph, END\\n\\nfrom langchain_openai import ChatOpenAI\\n\\nfrom typing import TypedDict, Annotated\\n\\nimport operator\\n\\n# βββ Define state structure (data passed between nodes) ββββββββββββββββββββββββ\\n\\nclass ResearchState(TypedDict):\\n\\n topic: str# Research topic\\n\\n research_notes: str# Research notes\\n\\n draft: str# Draft\\n\\n review_feedback: str# Review comments\\n\\n final_report: str# Final Report\\n\\n revision_count: Annotated[int,operator.add]# Revision count (cumulative)\\n\\nllm = ChatOpenAI(model="gpt-4o")\\n\\n# βββ Define node functions βββββββββββββββββββββββββββββββββββββββββββββ\\n\\ndef research_node(state: ResearchState) ->dict:\\n\\n"""Node 1: Research Phase"""\\n\\n response = llm.invoke(\\n\\n f"Please conduct brief research on the following topic and list 5 key points:{state['topic']}"\\n\\n)\\n\\nreturn{"research_notes": response.content}\\n\\ndef write_node(state: ResearchState) ->dict:\\n\\n"""Node 2: Drafting"""\\n\\n prompt = f"""\\n\\n Topic:{state['topic']}\\n\\n Research Notes:{state['research_notes']}\\n\\n {'Previous review comments:' + state.get('review_feedback', '') if state.get('review_feedback') else ''}\\nPlease write a 300-word analysis report draft based on the above content.\\n\\n """\\n\\n response = llm.invoke(prompt)\\n\\nreturn{"draft": response.content,"revision_count": 1}\\n\\ndef review_node(state: ResearchState) ->dict:\\n\\n"""Node 3: Draft Review"""\\n\\n response = llm.invoke(\\n\\n f"Review the following report; reply if the quality meets the standards 'APPROVED'οΌOtherwise, provide specific revision suggestions: nn{state['draft']}"\\n\\n)\\n\\nreturn{"review_feedback": response.content}\\n\\ndef finalize_node(state: ResearchState) ->dict:\\n\\n"""Node 4: Final Draft"""\\n\\nreturn{"final_report": state}\\n\\n# βββ Routing function: decide which path to take after review βββββββββββββββββββββββββββββ\\n\\ndef should_revise(state: ResearchState) ->str:\\n\\nif"APPROVED"in state:\\n\\nreturn"finalize"# β Final Version\\n\\nelif state>=3:\\n\\nreturn"finalize"# β Force termination if revisions exceed 3\\n\\nelse:\\n\\nreturn"revise"# β Return to the writing node for revisions\\n\\n# βββ Build workflow graph βββββββββββββββββββββββββββββββββββββββββββββ\\n\\n workflow = StateGraph(ResearchState)\\n\\n# Add nodes\\n\\n workflow.add_node("research",research_node)\\n\\n workflow.add_node("write", write_node)\\n\\n workflow.add_node("review",review_node)\\n\\n workflow.add_node("finalize",finalize_node)\\n\\n# Set entry point\\n\\n workflow.set_entry_point("research")\\n\\n# Add edges (define flow logic)
YouTip