Skip to main content
Article
langchainllm-frameworkchainslcelpythonorchestrationopenai

Build Your First LLM Chain with LangChain

Get started with LangChain by building a simple, powerful LLM chain. Learn to combine a prompt, a model, and an output parser using the LangChain Expression Language (LCEL) to generate structured responses.

beginner15 min4 steps
The play
  1. Install LangChain & Set API Key
    Install the core LangChain library and the OpenAI integration. LangChain is modular, so you install provider-specific packages separately. Set your OpenAI API key as an environment variable for authentication.
  2. Define Chain Components
    Import and instantiate the basic building blocks for your chain. You'll need a `ChatPromptTemplate` to format user input, a `ChatOpenAI` model to call the LLM, and a `StrOutputParser` to convert the model's message into a simple string.
  3. Compose with LangChain Expression Language (LCEL)
    Use the pipe `|` operator to compose your components into a runnable chain. This is the core of the LangChain Expression Language (LCEL), creating a clear, linear flow of data from prompt to model to parser.
  4. Invoke the Chain
    Run your chain using the `.invoke()` method. Pass a dictionary with keys that match the input variables in your prompt template (in this case, 'topic'). The chain will execute and return the final parsed output.
Starter code
# Save this as 'app.py' and run 'python app.py'
# Make sure you have set your OPENAI_API_KEY environment variable.

import os
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser

def main():
    # Check if the API key is set
    if not os.getenv("OPENAI_API_KEY"):
        print("Error: OPENAI_API_KEY environment variable not set.")
        return

    # 1. Define the Prompt Template
    # This structures the input to the model.
    prompt = ChatPromptTemplate.from_template("Tell me a short joke about {topic}")

    # 2. Instantiate the Model
    # We'll use OpenAI's gpt-3.5-turbo model.
    model = ChatOpenAI(model="gpt-3.5-turbo")

    # 3. Define the Output Parser
    # This will parse the model's chat message output into a string.
    output_parser = StrOutputParser()

    # 4. Create the Chain using LangChain Expression Language (LCEL)
    # The pipe operator `|` chains the components together.
    chain = prompt | model | output_parser

    # 5. Invoke the Chain
    # We pass the input topic to the chain and print the result.
    print("Invoking chain...")
    topic = "computers"
    response = chain.invoke({"topic": topic})

    print(f"\nJoke about '{topic}':")
    print(response)

if __name__ == "__main__":
    main()
Build Your First LLM Chain with LangChain — Action Pack