0Pricing
AI Agents with LangChain & Autonomous Workflows · บทเรียน

การปรับแต่งตรรกะของเชน

ค้นพบวิธีสร้างเชนแบบกำหนดเองและผสานฟังก์ชันกับตรรกะ Python ของคุณเองไว้ในเวิร์กโฟลว์ LangChain

การปรับแต่งตรรกะของเชน เป็นบทเรียน AI Agents with LangChain & Autonomous Workflows ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents with LangChain & Autonomous Workflows และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Beyond Standard Chains

In previous lessons, you learned how to create sequential chains to perform multi-step operations. These chains are powerful for connecting standard LangChain components like prompts and LLMs.

But what if you need to do something unique? What if you need to process data in a specific way before it reaches your LLM, or format its output afterward?

When to Add Custom Steps

Standard chains are great, but they can't handle every scenario. Custom logic allows you to:

  • Pre-process inputs: Clean, validate, or transform user input before sending it to a prompt or LLM.
  • Post-process outputs: Parse, filter, or reformat LLM responses for display or further use.
  • Integrate external logic: Call your own Python functions, external APIs, or apply conditional routing.
  • Handle complex data transformations: Convert data types, merge information, or apply business rules.

Introducing RunnableLambda

LangChain's RunnableLambda is your key to integrating custom Python functions into chains. It wraps any Python callable (like a function or a lambda expression) and makes it behave like a LangChain Runnable component.

This means you can seamlessly insert your own Python logic anywhere in a chain, just like you would an LLM or a prompt template!

Your First Custom Function

Let's start with a simple custom function that adds an exclamation mark to a string. We'll wrap it with RunnableLambda to make it part of a chain.

Try running this basic example:

from langchain_core.runnables import RunnableLambda

def add_exclamation(text: str) -> str:
    return text + "!"

if __name__ == "__main__":
    # Wrap your function to make it a Runnable
    custom_step = RunnableLambda(add_exclamation)
    
    # Invoke it like any other Runnable
    result = custom_step.invoke("Hello CoddyKit")
    print(result)

Chaining Custom Logic

The real power comes when you combine RunnableLambda with other LangChain components. You can place your custom logic at the beginning, middle, or end of a chain.

For example, you might have a custom function that prepares the input for a prompt, or one that processes the output from an LLM.

Custom Pre-processing Chain

Here's an example where a custom step pre-processes the input by converting it to uppercase before it's passed to a PromptTemplate and then to a simulated LLM.

Notice how the `uppercase_input` function expects a dictionary, mirroring how chain inputs often work.

from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnableLambda
from langchain_community.llms import FakeListLLM

def uppercase_input(data: dict) -> dict:
    # Ensure 'text' key exists and convert its value to uppercase
    return {"text": data.get("text", "").upper()}

if __name__ == "__main__":
    # A simulated LLM for demonstration
    llm = FakeListLLM(responses=["I received your uppercase text!"])

    # Define a simple prompt template
    prompt = PromptTemplate.from_template(
        "You mentioned: {text}. What do you think?"
    )

    # Create the custom pre-processing step
    pre_process_step = RunnableLambda(uppercase_input)

    # Build the chain: custom_step -> prompt -> llm
    custom_chain = pre_process_step | prompt | llm

    # Invoke the chain with lowercase input
    input_data = {"text": "hello world"}
    response = custom_chain.invoke(input_data)
    print(response)

Custom Post-processing Logic

Just as you can pre-process inputs, you can also post-process the outputs from an LLM. This is useful for:

  • Extracting specific information from a longer response.
  • Formatting the output for display in a UI.
  • Converting the output to a different data structure (e.g., JSON).
  • Adding a custom header or footer to the LLM's message.

Example: Custom Output Formatting

Let's create a custom function that takes the raw LLM response and wraps it with a friendly message. This makes the output more user-friendly.

Run this example to see the LLM's response being transformed:

from langchain_core.runnables import RunnableLambda
from langchain_community.llms import FakeListLLM

def format_llm_output(llm_response: str) -> str:
    # Add a custom prefix and suffix to the LLM's message
    return f"🤖 AI says: '{llm_response.strip()}' - Over and out!"

if __name__ == "__main__":
    # A simulated LLM for demonstration
    llm = FakeListLLM(responses=["The weather is sunny today."])

    # Create the custom post-processing step
    post_process_step = RunnableLambda(format_llm_output)

    # Build the chain: llm -> custom_step
    custom_chain = llm | post_process_step

    # Invoke the chain (input doesn't affect FakeListLLM's response here)
    response = custom_chain.invoke("What's the weather like?")
    print(response)

Adding Conditional Logic

RunnableLambda isn't just for simple transformations. You can embed complex Python logic, including conditionals, loops, and even calls to other services, directly into your chain.

For instance, you could have a custom step that checks if an input meets certain criteria and, if not, redirects the flow or returns a default message, creating dynamic and intelligent workflows.

Quick Check: Custom Chain Steps

Which of the following are good use cases for integrating custom Python logic (e.g., using RunnableLambda) into a LangChain workflow?

Recap & Next Steps

You've learned how to inject your own Python functions and logic into LangChain workflows using RunnableLambda. This powerful feature allows you to:

  • Perform custom pre-processing on inputs.
  • Apply custom post-processing to LLM outputs.
  • Integrate complex or conditional logic within your chains.

By mastering custom chain logic, you gain immense flexibility to tailor LangChain to your exact needs, building truly unique and intelligent applications. Next, explore how to use pre-built toolkits to add even more capabilities to your agents!

คำถามที่พบบ่อย

บทเรียน “การปรับแต่งตรรกะของเชน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การปรับแต่งตรรกะของเชน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents with LangChain & Autonomous Workflows ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การปรับแต่งตรรกะของเชน”

ค้นพบวิธีสร้างเชนแบบกำหนดเองและผสานฟังก์ชันกับตรรกะ Python ของคุณเองไว้ในเวิร์กโฟลว์ LangChain คุณปฏิบัติ AI Agents with LangChain & Autonomous Workflows ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents with LangChain & Autonomous Workflows หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents with LangChain & Autonomous Workflows บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การปรับแต่งตรรกะของเชน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม

ได้ บทเรียน AI Agents with LangChain & Autonomous Workflows ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. บทนำสู่เชนของ LangChain
  2. เชนแบบลำดับและเชนอย่างง่าย
  3. การปรับแต่งตรรกะของเชน
  4. การกำหนดเส้นทางและสายงานแบบมีเงื่อนไข
← กลับไปที่ AI Agents with LangChain & Autonomous Workflows