Creating Runnable objects with chain decorator
Author: Yejin Park
Peer Review:
Proofread : Chaeyoon Kim
This is a part of LangChain Open Tutorial
Overview
This tutorial explains how to convert regular functions into Runnable objects using the @chain decorator.
We'll cover ChatPromptTemplate for prompt creation, function transformation with @chain.
The practical exercise demonstrates how to builde a custom chain that converts text into Instagram-style posts with emojis.
Table of Contents
References
Environment Setup
Setting up your environment is the first step. See the Environment Setup guide for more details.
[Note]
The
langchain-opentutorialis a bundle of easy-to-use environment setup guidance, useful functions and utilities for tutorials.Check out the
langchain-opentutorialfor more details.
You can set API keys in a .env file or set them manually.
[Note] If youβre not using the .env file, no worries! Just enter the keys directly in the cell below, and youβre good to go.
Creating Runnable objects: RunnableLambda vs. chain decorator
As highlighted in LangChain's Conceptual guide, the Runnable interface is a core concept going with many LangChain components. When we use LangChain Expression Language (LCEL) to create a Runnable, we often call it a chain. This means that chains are a specific type of Runnable and therefore inherit all the properties and methods of a Runnable object.
You can create these objects from regular Python functions using two primary methods: RunnableLambda and the @chain decorator.
Let's see how it works in practice!
Define two prompt templates using the ChatPromptTemplate class:
prompt1requests a brief description of a given topic.prompt2requests the creation of an Instagram post using emojis.
Using the RunnableLambda
Let's check the following example, wrapping a regular function instagram_post_generator() with RunnableLambda to create a Runnable object.
Using the chain decorator
You can convert any function into a chain by adding the @chain decorator.
This does the same thing as wrapping the function in RunnableLambda. However, the @chain decorator provides a cleaner and more maintainable way to create Runnable objects in your LangChain applications.
The custom_chain function executes a custom chain based on the input text.
By decorating this function with
@chain, we convert it into a Runnable object.
Since custom_chain is now a Runnable object, it must be executed using invoke().
Last updated