LangChain OpenTutorial
  • πŸ¦œοΈπŸ”— The LangChain Open Tutorial for Everyone
  • 01-Basic
    • Getting Started on Windows
    • 02-Getting-Started-Mac
    • OpenAI API Key Generation and Testing Guide
    • LangSmith Tracking Setup
    • Using the OpenAI API (GPT-4o Multimodal)
    • Basic Example: Prompt+Model+OutputParser
    • LCEL Interface
    • Runnable
  • 02-Prompt
    • Prompt Template
    • Few-Shot Templates
    • LangChain Hub
    • Personal Prompts for LangChain
    • Prompt Caching
  • 03-OutputParser
    • PydanticOutputParser
    • PydanticOutputParser
    • CommaSeparatedListOutputParser
    • Structured Output Parser
    • JsonOutputParser
    • PandasDataFrameOutputParser
    • DatetimeOutputParser
    • EnumOutputParser
    • Output Fixing Parser
  • 04-Model
    • Using Various LLM Models
    • Chat Models
    • Caching
    • Caching VLLM
    • Model Serialization
    • Check Token Usage
    • Google Generative AI
    • Huggingface Endpoints
    • HuggingFace Local
    • HuggingFace Pipeline
    • ChatOllama
    • GPT4ALL
    • Video Q&A LLM (Gemini)
  • 05-Memory
    • ConversationBufferMemory
    • ConversationBufferWindowMemory
    • ConversationTokenBufferMemory
    • ConversationEntityMemory
    • ConversationKGMemory
    • ConversationSummaryMemory
    • VectorStoreRetrieverMemory
    • LCEL (Remembering Conversation History): Adding Memory
    • Memory Using SQLite
    • Conversation With History
  • 06-DocumentLoader
    • Document & Document Loader
    • PDF Loader
    • WebBaseLoader
    • CSV Loader
    • Excel File Loading in LangChain
    • Microsoft Word(doc, docx) With Langchain
    • Microsoft PowerPoint
    • TXT Loader
    • JSON
    • Arxiv Loader
    • UpstageDocumentParseLoader
    • LlamaParse
    • HWP (Hangeul) Loader
  • 07-TextSplitter
    • Character Text Splitter
    • 02. RecursiveCharacterTextSplitter
    • Text Splitting Methods in NLP
    • TokenTextSplitter
    • SemanticChunker
    • Split code with Langchain
    • MarkdownHeaderTextSplitter
    • HTMLHeaderTextSplitter
    • RecursiveJsonSplitter
  • 08-Embedding
    • OpenAI Embeddings
    • CacheBackedEmbeddings
    • HuggingFace Embeddings
    • Upstage
    • Ollama Embeddings With Langchain
    • LlamaCpp Embeddings With Langchain
    • GPT4ALL
    • Multimodal Embeddings With Langchain
  • 09-VectorStore
    • Vector Stores
    • Chroma
    • Faiss
    • Pinecone
    • Qdrant
    • Elasticsearch
    • MongoDB Atlas
    • PGVector
    • Neo4j
    • Weaviate
    • Faiss
    • {VectorStore Name}
  • 10-Retriever
    • VectorStore-backed Retriever
    • Contextual Compression Retriever
    • Ensemble Retriever
    • Long Context Reorder
    • Parent Document Retriever
    • MultiQueryRetriever
    • MultiVectorRetriever
    • Self-querying
    • TimeWeightedVectorStoreRetriever
    • TimeWeightedVectorStoreRetriever
    • Kiwi BM25 Retriever
    • Ensemble Retriever with Convex Combination (CC)
  • 11-Reranker
    • Cross Encoder Reranker
    • JinaReranker
    • FlashRank Reranker
  • 12-RAG
    • Understanding the basic structure of RAG
    • RAG Basic WebBaseLoader
    • Exploring RAG in LangChain
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
    • Conversation-With-History
    • Translation
    • Multi Modal RAG
  • 13-LangChain-Expression-Language
    • RunnablePassthrough
    • Inspect Runnables
    • RunnableLambda
    • Routing
    • Runnable Parallel
    • Configure-Runtime-Chain-Components
    • Creating Runnable objects with chain decorator
    • RunnableWithMessageHistory
    • Generator
    • Binding
    • Fallbacks
    • RunnableRetry
    • WithListeners
    • How to stream runnables
  • 14-Chains
    • Summarization
    • SQL
    • Structured Output Chain
    • StructuredDataChat
  • 15-Agent
    • Tools
    • Bind Tools
    • Tool Calling Agent
    • Tool Calling Agent with More LLM Models
    • Iteration-human-in-the-loop
    • Agentic RAG
    • CSV/Excel Analysis Agent
    • Agent-with-Toolkits-File-Management
    • Make Report Using RAG, Web searching, Image generation Agent
    • TwoAgentDebateWithTools
    • React Agent
  • 16-Evaluations
    • Generate synthetic test dataset (with RAGAS)
    • Evaluation using RAGAS
    • HF-Upload
    • LangSmith-Dataset
    • LLM-as-Judge
    • Embedding-based Evaluator(embedding_distance)
    • LangSmith Custom LLM Evaluation
    • Heuristic Evaluation
    • Compare experiment evaluations
    • Summary Evaluators
    • Groundedness Evaluation
    • Pairwise Evaluation
    • LangSmith Repeat Evaluation
    • LangSmith Online Evaluation
    • LangFuse Online Evaluation
  • 17-LangGraph
    • 01-Core-Features
      • Understanding Common Python Syntax Used in LangGraph
      • Title
      • Building a Basic Chatbot with LangGraph
      • Building an Agent with LangGraph
      • Agent with Memory
      • LangGraph Streaming Outputs
      • Human-in-the-loop
      • LangGraph Manual State Update
      • Asking Humans for Help: Customizing State in LangGraph
      • DeleteMessages
      • DeleteMessages
      • LangGraph ToolNode
      • LangGraph ToolNode
      • Branch Creation for Parallel Node Execution
      • Conversation Summaries with LangGraph
      • Conversation Summaries with LangGraph
      • LangGrpah Subgraph
      • How to transform the input and output of a subgraph
      • LangGraph Streaming Mode
      • Errors
      • A Long-Term Memory Agent
    • 02-Structures
      • LangGraph-Building-Graphs
      • Naive RAG
      • Add Groundedness Check
      • Adding a Web Search Module
      • LangGraph-Add-Query-Rewrite
      • Agentic RAG
      • Adaptive RAG
      • Multi-Agent Structures (1)
      • Multi Agent Structures (2)
    • 03-Use-Cases
      • LangGraph Agent Simulation
      • Meta Prompt Generator based on User Requirements
      • CRAG: Corrective RAG
      • Plan-and-Execute
      • Multi Agent Collaboration Network
      • Multi Agent Collaboration Network
      • Multi-Agent Supervisor
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • SQL-Agent
      • 10-LangGraph-Research-Assistant
      • LangGraph Code Assistant
      • Deploy on LangGraph Cloud
      • Tree of Thoughts (ToT)
      • Ollama Deep Researcher (Deepseek-R1)
      • Functional API
      • Reflection in LangGraph
  • 19-Cookbook
    • 01-SQL
      • TextToSQL
      • SpeechToSQL
    • 02-RecommendationSystem
      • ResumeRecommendationReview
    • 03-GraphDB
      • Movie QA System with Graph Database
      • 05-TitanicQASystem
      • Real-Time GraphRAG QA
    • 04-GraphRAG
      • Academic Search System
      • Academic QA System with GraphRAG
    • 05-AIMemoryManagementSystem
      • ConversationMemoryManagementSystem
    • 06-Multimodal
      • Multimodal RAG
      • Shopping QnA
    • 07-Agent
      • 14-MoARAG
      • CoT Based Smart Web Search
      • 16-MultiAgentShoppingMallSystem
      • Agent-Based Dynamic Slot Filling
      • Code Debugging System
      • New Employee Onboarding Chatbot
      • 20-LangGraphStudio-MultiAgent
      • Multi-Agent Scheduler System
    • 08-Serving
      • FastAPI Serving
      • Sending Requests to Remote Graph Server
      • Building a Agent API with LangServe: Integrating Currency Exchange and Trip Planning
    • 08-SyntheticDataset
      • Synthetic Dataset Generation using RAG
    • 09-Monitoring
      • Langfuse Selfhosting
Powered by GitBook
On this page
  • Overview
  • Table of Contents
  • References
  • Environment Setup
  • Creating Runnable objects: RunnableLambda vs. chain decorator
  • Using the RunnableLambda
  • Using the chain decorator
  1. 13-LangChain-Expression-Language

Creating Runnable objects with chain decorator

PreviousConfigure-Runtime-Chain-ComponentsNextRunnableWithMessageHistory

Last updated 28 days ago

  • Author:

  • Peer Review:

  • Proofread :

  • This is a part of

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

[Note]

  • The langchain-opentutorial is a bundle of easy-to-use environment setup guidance, useful functions and utilities for tutorials.

%%capture --no-stderr
%pip install langchain-opentutorial
# Install required packages
from langchain_opentutorial import package

package.install(
    [
        "langchain_core",
        "langchain_openai",
    ],
    verbose=False,
    upgrade=False,
)

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.

from dotenv import load_dotenv
from langchain_opentutorial import set_env

# Attempt to load environment variables from a .env file; if unsuccessful, set them manually.
if not load_dotenv():
    set_env(
        {
            "OPENAI_API_KEY": "",
            "LANGCHAIN_API_KEY": "",
            "LANGCHAIN_TRACING_V2": "true",
            "LANGCHAIN_ENDPOINT": "https://api.smith.langchain.com",
            "LANGCHAIN_PROJECT": "07-ChainDecorator",
        }
    )

Creating Runnable objects: RunnableLambda vs. chain decorator

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:

  • prompt1 requests a brief description of a given topic.

  • prompt2 requests the creation of an Instagram post using emojis.

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import chain
from langchain_openai import ChatOpenAI

# Define prompt templates
prompt1 = ChatPromptTemplate.from_template("Please provide a brief description in English about {topic}.")
prompt2 = ChatPromptTemplate.from_template(
    "Please create an Instagram post using emojis for the following text: {sentence}"
)

Using the RunnableLambda

Let's check the following example, wrapping a regular function instagram_post_generator() with RunnableLambda to create a Runnable object.

from langchain_core.runnables import RunnableLambda

# Using RunnableLambda
def instagram_post_generator(text):
    chain1 = prompt1 | ChatOpenAI(model="gpt-4o-mini") | StrOutputParser()
    output1 = chain1.invoke({"topic": text})
    chain2 = prompt2 | ChatOpenAI(model="gpt-4o-mini") | StrOutputParser()
    return chain2.invoke({"sentence": output1})

runnable_chain = RunnableLambda(instagram_post_generator)
print(runnable_chain.invoke("quantum mechanics"))
🌌✨ Dive into the fascinating world of quantum mechanics! πŸ”¬πŸ’« 
    
    🧬 This fundamental branch of physics explores the behavior of matter and energy at the tiniest scalesβ€”think atoms and subatomic particles! βš›οΈπŸ’₯
    
    πŸ“ Unlike classical mechanics, quantum mechanics introduces mind-bending concepts like:
    πŸŒŠπŸŒ€ Wave-particle duality (particles can be both wave-like and particle-like!),
    πŸ”„ Superposition (particles can exist in multiple states at once!),
    πŸ”— Entanglement (where particles are interconnected across distances! 😲)
    
    πŸ” These principles reshape our understanding of reality and fuel groundbreaking technologies such as:
    πŸ’» Quantum computing,
    πŸ’‘ Lasers,
    πŸ”Œ Semiconductors!
    
    Join us on this journey to unravel the mysteries of the quantum realm! πŸŒŸπŸ”­ #QuantumMechanics #Physics #ScienceIsCool #WaveParticleDuality #QuantumComputing #Entanglement #Superposition #Technology #NatureOfReality

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.

@chain
def custom_chain(text):
    # Create a chain by connecting the first prompt, ChatOpenAI, and string output parser
    chain1 = prompt1 | ChatOpenAI(model="gpt-4o-mini") | StrOutputParser()
    output1 = chain1.invoke({"topic": text})

    # Create a chain by connecting the second prompt, ChatOpenAI, and string output parser
    chain2 = prompt2 | ChatOpenAI(model="gpt-4o-mini") | StrOutputParser()
    # Call the second chain with the parsed first result and return the final result
    return chain2.invoke({"sentence": output1})

Since custom_chain is now a Runnable object, it must be executed using invoke().

# Call custom_chain
print(custom_chain.invoke("quantum mechanics"))
🌌✨ Dive into the mysterious world of #QuantumMechanics! πŸ”¬πŸ’« 
    
    This fundamental branch of physics reveals how matter and energy behave at the tiniest scales, like atoms and subatomic particles. πŸ§¬βš›οΈ 
    
    πŸŒ€ **Wave-Particle Duality**: Electrons can be both waves and particles! πŸŒŠβž‘οΈβš›οΈ 
    
    πŸ”„ **Superposition**: Systems can exist in multiple states at once! 🎭✨ 
    
    πŸ”— **Entanglement**: Particles can be connected in a way that the state of one affects the other, no matter the distance! 🌌❀️ 
    
    These mind-blowing concepts are shaping our understanding of the universe and powering technologies like semiconductors, lasers, and quantum computing! πŸ’»πŸ”‹ 
    
    #Physics #Science #Universe #Technology #Innovation #Quantum #ExploreTheUnknown πŸš€πŸ”πŸ§ͺ

Setting up your environment is the first step. See the guide for more details.

Check out the for more details.

As highlighted in LangChain's , 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.

LangChain: Runnable interface
LangChain: LangChain Expression Language (LCEL)
LangChain: The convenience @chain decorator
RunnableLambda API Reference
Chain API Referece
Environment Setup
langchain-opentutorial
Conceptual guide
Yejin Park
Chaeyoon Kim
LangChain Open Tutorial
Overview
Environement Setup
Creating Runnable objects: RunnableLambda vs chain decorator
Using the RunnableLambda
Using the chain decorator