Master LangChain in 10 Minutes: From Basics to Advanced AI Engineering
This guide walks AI engineers through a rapid 10‑minute boot‑strap of LangChain, explaining its purpose, core concepts, design questions, environment setup, and step‑by‑step code examples that cover APIs, chains, memory, retrieval‑augmented generation, tools, agents, and the overall architecture.
LangChain is an open‑source framework for building AI‑centric applications by chaining large language models (LLMs) with other components. This article serves as a "10‑minute quick‑start" manual, introducing LangChain from an engineering perspective and helping readers bootstrap AI projects.
1. Introduction
LangChain was launched in October 2022 by Harrison Chase at Harvard. It aims to simplify the construction of LLM‑driven applications by providing reusable components such as models, prompts, indexes, memory, chains, and agents.
2. What is AI Engineering?
Engineering is defined as the organized transformation of existing entities into products that meet specific goals. In AI engineering, the goal is a concrete AI user need (e.g., content creation, Q&A, image recognition), the "person" is the developer or team, the science/technology includes LLMs and related tools, and the entities are documents, knowledge bases, or business data.
Goal: Specific AI user requirement.
Person: Developers or AI teams.
Science | Technology: LLMs and supporting services.
Entity: Existing documents, knowledge bases, business data.
Product: Chatbots, content generators, etc.
3. Designing LangChain
Key design questions include:
What problems does LangChain solve?
How should its API boost AI engineer productivity?
How to abstract core components for extensibility?
Answers:
LangChain extends LLM capabilities, acting as the "body" that handles tasks beyond pure generation.
It provides LCEL (LangChain Expression Language) for declarative programming.
It defines six core abstractions: Models, Prompts, Indexes, Memory, Chains, Agents.
4. Environment Preparation
Python ≥ 3.8 (download from python.org )
OpenAI API key (set export OPENAI_API_KEY="<Your-OpenAI-SK>")
Install LangChain:
pip install langchain langchain-openai5. Design Evolution
5.1 API Layer
OpenAI’s Chat Completion API is the core entry point. Example:
import os, requests
api_key = os.getenv('OPENAI_API_KEY')
headers = {'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}'}
data = {'model': 'gpt-4', 'messages': [{'role': 'user', 'content': '什么是图计算?'}], 'temperature': 0.7}
url = 'https://api.openai.com/v1/chat/completions'
response = requests.post(url, json=data, headers=headers)
answer = response.json()['choices'][0]['message']['content']
print(answer)Output demonstrates a concise answer about graph computation.
5.2 SDK Layer
Using langchain-openai reduces boilerplate:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model_name='gpt-4')
response = llm.invoke('什么是图计算?')
print(response)5.3 IO Abstraction
LangChain introduces Prompt and OutputParser to handle input formatting and output parsing, avoiding repetitive string handling.
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_template('{question}')
output_parser = StrOutputParser()
chain = prompt | llm | output_parser
answer = chain.invoke({'question': '什么是图计算?'})
print(answer)5.4 Memory
Memory components (e.g., ConversationBufferMemory) store chat history, enabling multi‑turn interactions.
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
prompt = ChatPromptTemplate.from_messages([
MessagesPlaceholder(variable_name='chat_history'),
HumanMessagePromptTemplate.from_template('{question}')
])
llm_chain = LLMChain(llm=llm, memory=memory, prompt=prompt)
print(llm_chain.predict(question='什么是图计算?'))
print(llm_chain.predict(question='刚才我问了什么问题?'))5.5 Retrieval‑Augmented Generation (RAG)
RAG combines external document retrieval with LLM prompting to reduce hallucinations. Core components include DocumentLoader, TextSplitter, EmbeddingsModel, VectorStore, and Retriever.
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores.faiss import FAISS
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
docs = [Document(page_content='TuGraph是蚂蚁开源的图数据库产品')]
splits = RecursiveCharacterTextSplitter().split_documents(docs)
vector_store = FAISS.from_documents(splits, OpenAIEmbeddings())
retriever = vector_store.as_retriever()
prompt = ChatPromptTemplate.from_template('基于上下文:{context}
回答:{input}')
chain = ({'context': retriever, 'input': RunnablePassthrough()} | prompt | llm | StrOutputParser())
print(chain.invoke('蚂蚁图数据库开源了吗?'))5.6 Tools
LangChain’s @tool decorator lets developers expose functions to LLMs. Example of a temperature‑fetching tool:
import random
from langchain_core.tools import tool
@tool
def get_temperature(city: str) -> int:
"""获取指定城市的当前气温"""
return random.randint(-20, 50)
llm = ChatOpenAI(model_name='gpt-4')
chain = RunnablePassthrough() | llm.bind_tools(tools=[get_temperature]) | JsonOutputToolsParser()
print(chain.invoke('杭州今天多少度?'))5.7 Agents
Agents use LLM reasoning to decide which actions (tools) to invoke, enabling autonomous workflows.
from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate, SystemMessagePromptTemplate
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template('You are a helpful assistant'),
MessagesPlaceholder(variable_name='chat_history', optional=True),
HumanMessagePromptTemplate.from_template('{input}'),
MessagesPlaceholder(variable_name='agent_scratchpad')
])
tools = [get_temperature]
agent = create_openai_tools_agent(llm, tools, prompt=prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
print(agent_executor.invoke({'input': '今天杭州多少度?'})['output'])6. LangChain Architecture Overview
The framework consists of layers from low‑level LLM APIs up to high‑level agents, with optional components such as LangServe (REST deployment) and LangGraph (graph‑based workflows supporting loops).
7. Conclusion
By following this guide, developers can quickly grasp LangChain’s design philosophy, build end‑to‑end AI pipelines, and extend them with memory, RAG, tools, and agents to create sophisticated AI applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Alibaba Cloud Developer
Alibaba's official tech channel, featuring all of its technology innovations.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
