체인 로직 사용자 지정
사용자 지정 체인을 구축하고 자체 Python 함수와 로직을 LangChain 작업 흐름에 통합하는 방법을 알아봅니다.
체인 로직 사용자 지정은(는) CoddyKit의 무료 AI Agents with LangChain & Autonomous Workflows 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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!
자주 묻는 질문
“체인 로직 사용자 지정” 강의는 무료인가요?
네 — “체인 로직 사용자 지정” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents with LangChain & Autonomous Workflows 강의 전체를 잠금 해제할 수 있습니다. AI Agents with LangChain & Autonomous Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.
“체인 로직 사용자 지정”에서 뭘 배우나요?
사용자 지정 체인을 구축하고 자체 Python 함수와 로직을 LangChain 작업 흐름에 통합하는 방법을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents with LangChain & Autonomous Workflows을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents with LangChain & Autonomous Workflows을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents with LangChain & Autonomous Workflows은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“체인 로직 사용자 지정” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents with LangChain & Autonomous Workflows 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents with LangChain & Autonomous Workflows 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- LangChain 체인 입문
- 순차 체인과 단순 체인
- 체인 로직 사용자 지정
- 라우팅 및 조건부 체인