2 min read

Building LLM Chains with LangChain

This guide demonstrates how to build a simple sequential chain using LangChain. Chains allow you to combine multiple LLM calls or other utilities into a single, coherent workflow. In this example, we will create a chain that first generates a company name based on a product, and then writes a short description for that company.

Modules Used:

  • langchain: The framework for developing applications powered by language models.
  • langchain_openai: The integration package for OpenAI models.
  • python-dotenv: To securely manage the API key.
  • argparse: To handle command-line arguments.

Prerequisites

  1. OpenAI API Key: You need an API key from OpenAI.

Installation

pip install langchain langchain-openai python-dotenv

Setup

Create a .env file in your project directory:

OPENAI_API_KEY=sk-your-actual-api-key-here

The Code

Save this as chain_demo.py.

import os
import argparse
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough

# 1. Load Config
load_dotenv()
if not os.getenv("OPENAI_API_KEY"):
    print("Error: OPENAI_API_KEY not found in .env file.")
    exit(1)

# 2. Initialize Model
model = ChatOpenAI(model="gpt-3.5-turbo")

def run_chain(product):
    # 3. Define Prompts
    # Step 1: Generate a company name
    name_prompt = ChatPromptTemplate.from_template(
        "What is a good name for a company that makes {product}?"
    )

    # Step 2: Write a description for that company
    description_prompt = ChatPromptTemplate.from_template(
        "Write a 20-word description for a company named {company_name} that makes {product}."
    )

    # 4. Build the Chain using LCEL (LangChain Expression Language)
    # The output of the first chain (company_name) is passed to the second prompt
    chain = (
        {"product": RunnablePassthrough()} 
        | name_prompt 
        | model 
        | StrOutputParser() 
        | (lambda output: {"company_name": output, "product": product})
        | description_prompt
        | model
        | StrOutputParser()
    )

    print(f"Generating chain for product: '{product}'...\n")
    result = chain.invoke(product)
    print(f"Result:\n{result}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="LangChain LLM Chain Demo")
    parser.add_argument("product", help="The product to generate a company for (e.g., 'colorful socks')")

    args = parser.parse_args()

    run_chain(args.product)

Usage

python chain_demo.py "eco-friendly water bottles"

programming/python/python