What is LangChain

LangChain is an open-source framework for building LLM-driven applications. It provides core capabilities such as chaining, Agent management, memory systems, and tool integration, enabling developers to quickly build complex AI applications. The emergence of LangChain has significantly lowered the barrier to AI application development.

Core Concepts

  • Chain: Connects multiple components to form a processing pipeline
  • Agent: An AI that can autonomously decide which tools to use
  • Tool: External functions that an Agent can call
  • Memory: Maintains context across multiple conversations
  • Retriever: Retrieves relevant information from external knowledge bases

Environment Setup

pip install langchain langchain-openai langchain-community

# Set API key
export DEEPSEEK_API_KEY="your-api-key"

Building Your First Chain

from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser

# Initialize the model
llm = ChatOpenAI(
    model="deepseek-chat",
    base_url="https://api.deepseek.com/v1",
    api_key="your-api-key"
)

# Create a prompt template
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a {role} skilled in {skill}"),
    ("user", "{input}")
])

# Create a chain
chain = prompt | llm | StrOutputParser()

# Run
result = chain.invoke({
    "role": "Python Programming Mentor",
    "skill": "explain programming concepts in an easy-to-understand way",
    "input": "What is a decorator?"
})
print(result)

Building a Conversational App with Memory

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

memory = ConversationBufferMemory(return_messages=True)

conversation = ConversationChain(
    llm=llm,
    memory=memory,
    verbose=True
)

# Multi-turn conversation
conversation.predict(input="My name is Xiao Ming")
conversation.predict(input="I like programming")
conversation.predict(input="What did I say my name was?")
# The model will remember what was said earlier

Building a RAG Application

from langchain.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
from langchain.chains import RetrievalQA

# Load web content
loader = WebBaseLoader("https://docs.python.org/3/tutorial/")
docs = loader.load()

# Split text
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_documents(docs)

# Create vector store
vectorstore = Chroma.from_documents(
    chunks, OpenAIEmbeddings()
)

# Create QA chain
qa = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=vectorstore.as_retriever()
)

result = qa.run("How to handle exceptions in Python?")
print(result)

Next Steps for Learning

After mastering the basic concepts, you can delve into: the new syntax of LangChain Expression Language (LCEL), LangSmith for debugging and tracing, LangServe for deploying API services, and LangGraph for building complex Agent workflows. The LangChain ecosystem is rapidly evolving, so it's recommended to follow the official documentation for the latest information.