liveBook · Manning

LangChain

As explained in Data Analysis with LLMs

LangChain is an open-source software framework for developing applications that integrate language models with prompts, data, and external actions.

LangChain is a Python framework for applications that need more than a single language-model call. It connects components into chains: steps that can prepare a prompt, call a model, process its reply, or use another tool. For a simple task, a provider’s library may be enough; LangChain becomes more useful when the workflow has several connected parts. section 10.1 section 10.7

Classify customer reviews

Suppose a CSV file has a column of review text. A classification chain fills a prompt template with each review, asks a chat model whether its sentiment is positive or negative, and parses the reply into a string. Applying the chain to the reviews produces a result CSV with an added class column. The template specifies both the question and the permitted answers, rather than leaving the output format implicit. section 10.2.1 section 10.2.3

Listing 10.1 Sentiment classification using LangChain
from langchain_openai import ChatOpenAI
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.output_parsers.string import StrOutputParser
from langchain_core.runnables.passthrough import RunnablePassthrough

import argparse
import pandas as pd

def create_chain():                         #1
    """ Creates chain for text classification.
    
    Returns:
        a chain for text classification.
    """
    prompt = ChatPromptTemplate.from_template(  #2
        '{text}\n'
        'Is the sentiment positive or negative?\n'
        'Answer ("Positive"/"Negative")\n')
    llm = ChatOpenAI(              #3
        model='gpt-4o', temperature=0, 
        max_tokens=1)
    parser = StrOutputParser()  #4
     #5
    chain = ({'text':RunnablePassthrough()} | prompt | llm | parser)
    return chain

if __name__ == '__main__':
    
    parser = argparse.ArgumentParser()
    parser.add_argument('file_path', type=str, help='Path to input file')
    args = parser.parse_args()
    
    df = pd.read_csv(args.file_path)  #6

    chain = create_chain()            #7
    results = chain.batch(list(df['text']))  #8

    df['class'] = results  #9
    df.to_csv('result.csv')

The Python listing shows how a prompt template, ChatOpenAI model, and string output parser form the review-classification chain. section 10.2.3

When the next step depends on the question, an agent offers a different approach. Given suitable tools, it can choose which data source to access and in what order—for example, query an SQLite sales database and then search the web using a title found in the results. LangChain provides constructors for SQL agents and a way to load a web-search tool; that search tool also requires a SerpAPI account and access key. section 10.4 section 10.4.2

To try the classification example, install compatible LangChain and provider packages, then run the script against a reviews CSV and inspect its output file. Pinning versions matters here: LangChain’s interfaces were changing rapidly when these examples were written. section 10.1 section 10.2.4

How Data Analysis with LLMs covers it

How deep it goes
Works through a classification chain and an agent setup, but defers detailed coverage of the framework.
Examples
Uses CSV review sentiment classification and an agent that combines an SQLite sales database with web search.
What it assumes
Assumes basic Python and familiarity with prompts, while introducing chains through a short text-classification workflow.
What you can do after
Apply it via LangChain to classify reviews or configure an agent with SQL and web-search tools.
How it connects
Links prompt templates, output parsers, language models, agents, SQL databases, and web search.

Also explained in

Compare how 19 books explain LangChain →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Analysis with LLMs. The section links point to the parts of the book it draws on.