เชนแบบลำดับและเชนอย่างง่าย
เรียนรู้การสร้างเชนพื้นฐานสำหรับดำเนินงานตามลำดับ โดยส่งเอาต์พุตจากขั้นตอนหนึ่งไปเป็นอินพุตของขั้นตอนถัดไป
เชนแบบลำดับและเชนอย่างง่าย เป็นบทเรียน AI Agents with LangChain & Autonomous Workflows ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents with LangChain & Autonomous Workflows และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Chains: Steps in Order
In LangChain, chains allow you to combine multiple Large Language Model (LLM) calls and other utilities into a single, coherent application.
Think of them as a series of steps where the output of one step becomes the input for the next. This creates a powerful, automated workflow.
Sequential Chains are a specific type designed for tasks that require a strict, ordered execution of steps.
Meet the LLMChain
Before we build complex sequential chains, let's look at the basic building block: the LLMChain.
An LLMChain combines an LLM (like GPT-4) with a PromptTemplate. It takes an input, formats it using the template, sends it to the LLM, and returns the LLM's response.
- LLM: The language model that generates text.
- PromptTemplate: Defines how user input is structured for the LLM.
Running a Single LLMChain
Here's how you can create and run a simple LLMChain. We'll ask it to suggest a catchy name for a new tech product.
Notice how the PromptTemplate defines what we expect the LLM to do, and the chain executes it.
import os
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
# IMPORTANT: Set your OpenAI API key as an environment variable
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY_HERE"
# For local testing, ensure it's set before running.
def main():
# 1. Define the LLM
llm = ChatOpenAI(temperature=0.7)
# 2. Define the Prompt Template
prompt_template = PromptTemplate(
input_variables=["product_type"],
template="Suggest a catchy name for a new {product_type}."
)
# 3. Create the LLMChain
name_chain = LLMChain(llm=llm, prompt=prompt_template)
# 4. Run the chain
result = name_chain.invoke({"product_type": "AI assistant"})
print(f"Suggested Name: {result['text']}")
if __name__ == "__main__":
main()Introducing SimpleSequentialChain
What if you need to perform multiple steps, where each step builds on the previous one? That's where SimpleSequentialChain comes in.
It takes a list of chains and executes them in order. The single output from the first chain becomes the single input for the second chain, and so on.
It's ideal for straightforward, linear workflows.
Input-Output Flow
SimpleSequentialChain manages the flow automatically:
- You provide an initial input to the first chain.
- The first chain processes it and produces an output.
- This output automatically becomes the input for the second chain.
- This continues until the last chain, whose output is the final result of the
SimpleSequentialChain.
It's like an assembly line for AI tasks!
First Step: Name Generation
Let's build a two-step sequential chain. Our first step will be to generate a product name, similar to our previous LLMChain example.
We define an LLMChain for this purpose. We'll make sure its output is clearly defined using output_key for the next step.
import os
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
# IMPORTANT: Set your OpenAI API key as an environment variable
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY_HERE"
def main():
llm = ChatOpenAI(temperature=0.7)
# Chain 1: Generate a product name
prompt_name = PromptTemplate(
input_variables=["product_type"],
template="Suggest a catchy, short name for a new {product_type}. Response should only be the name."
)
chain_name = LLMChain(llm=llm, prompt=prompt_name, output_key="product_name")
# This chain will output a dictionary like {'product_type': '...', 'product_name': '...'}
# The 'product_name' will be passed to the next chain.
result = chain_name.invoke({"product_type": "smartwatch"})
print(f"Input: {result['product_type']}")
print(f"Output (product_name): {result['product_name']}")
if __name__ == "__main__":
main()Second Step: Slogan Generation
Now, let's create the second LLMChain. This chain will take the product_name generated by the first chain and create a slogan for it.
Notice how its input_variables matches the output_key from the previous chain. This is how SimpleSequentialChain knows how to connect them.
import os
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
# IMPORTANT: Set your OpenAI API key as an environment variable
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY_HERE"
def main():
llm = ChatOpenAI(temperature=0.7)
# Chain 2: Generate a slogan based on the product name
prompt_slogan = PromptTemplate(
input_variables=["product_name"],
template="Write a creative slogan for a product named {product_name}. Response should only be the slogan."
)
chain_slogan = LLMChain(llm=llm, prompt=prompt_slogan, output_key="slogan")
# Example of running this chain independently
result = chain_slogan.invoke({"product_name": "ChronoMind"})
print(f"Input: {result['product_name']}")
print(f"Output (slogan): {result['slogan']}")
if __name__ == "__main__":
main()Putting Chains Together
Finally, we combine our two LLMChains into a SimpleSequentialChain. We pass the initial input to the overall sequential chain, and it handles the rest!
We'll also set verbose=True to see the intermediate steps, which is great for debugging.
import os
from langchain.chains import LLMChain, SimpleSequentialChain
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
# IMPORTANT: Set your OpenAI API key as an environment variable
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY_HERE"
def main():
llm = ChatOpenAI(temperature=0.7)
# Chain 1: Generate a product name
prompt_name = PromptTemplate(
input_variables=["product_type"],
template="Suggest a catchy, short name for a new {product_type}. Response should only be the name."
)
chain_name = LLMChain(llm=llm, prompt=prompt_name, output_key="product_name")
# Chain 2: Generate a slogan
prompt_slogan = PromptTemplate(
input_variables=["product_name"],
template="Write a creative slogan for a product named {product_name}. Response should only be the slogan."
)
chain_slogan = LLMChain(llm=llm, prompt=prompt_slogan, output_key="slogan")
# Combine into a SimpleSequentialChain
overall_chain = SimpleSequentialChain(
chains=[chain_name, chain_slogan],
verbose=True # Set to True to see intermediate steps
)
# Run the overall chain with the initial input
final_result = overall_chain.invoke({"product_type": "AI-powered coffee maker"})
print("\n--- Final Result ---")
print(f"Product Slogan: {final_result['slogan']}")
if __name__ == "__main__":
main()Tracing Chain Execution
When verbose=True, LangChain prints out the steps taken by your chain. This is incredibly useful for:
- Understanding how inputs and outputs flow.
- Debugging unexpected results.
- Seeing which prompts are sent to the LLM.
It helps you visualize the 'assembly line' in action and ensures each step performs as expected.
Quick Chain Check
Consider a SimpleSequentialChain with three LLMChains: Chain A, Chain B, and Chain C, in that order.
Chain A has output_key='topic'.
Chain B has input_variables=['topic'] and output_key='outline'.
Chain C has input_variables=['outline'].
If the SimpleSequentialChain is invoked with {'initial_input': 'AI agents'}, which statement is true?
Recap: Simple Sequential Chains
Great job! In this lesson, you learned about:
- The basic
LLMChainas a building block. - How
SimpleSequentialChainlinks multiple chains together. - Passing outputs from one step as inputs to the next.
- Using
output_keyandinput_variablesfor flow. - Debugging chains with
verbose=True.
Next, you'll discover how to customize chain logic and integrate your own Python functions within LangChain workflows!
คำถามที่พบบ่อย
บทเรียน “เชนแบบลำดับและเชนอย่างง่าย” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “เชนแบบลำดับและเชนอย่างง่าย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents with LangChain & Autonomous Workflows ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “เชนแบบลำดับและเชนอย่างง่าย”
เรียนรู้การสร้างเชนพื้นฐานสำหรับดำเนินงานตามลำดับ โดยส่งเอาต์พุตจากขั้นตอนหนึ่งไปเป็นอินพุตของขั้นตอนถัดไป คุณปฏิบัติ AI Agents with LangChain & Autonomous Workflows ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents with LangChain & Autonomous Workflows หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents with LangChain & Autonomous Workflows บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “เชนแบบลำดับและเชนอย่างง่าย” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม
ได้ บทเรียน AI Agents with LangChain & Autonomous Workflows ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- บทนำสู่เชนของ LangChain
- เชนแบบลำดับและเชนอย่างง่าย
- การปรับแต่งตรรกะของเชน
- การกำหนดเส้นทางและสายงานแบบมีเงื่อนไข