LangChain Basics: Build AI Apps from Scratch
This tutorial walks beginners through Python fundamentals, LangChain installation, core components like prompt templates, chains, and retrieval, and culminates in a complete intelligent customer‑service chatbot, showing step‑by‑step code and practical tips for building AI applications.
Python basics
Variables and data types:
# string
name = "Xiaoming"
# number
age = 25
height = 1.75
# list
skills = ["Python", "AI", "LangChain"]
# dict
person = {"name": "Xiaoming", "age": 25}Function definition:
def greet(name):
return f"Hello, {name}!"
print(greet("Xiaoming")) # Output: Hello, Xiaoming!Install third‑party packages with pip:
pip install package_nameLangChain overview
Core concepts
Easily connect various large models (GPT, Claude, Wenxin Yiyan, etc.)
Build intelligent chatbots
Allow AI to access private data
Create automated workflows
Why use LangChain
Answer questions based on internal company documents
Automatically analyze customer feedback
Generate personalized marketing copy
Quick start
Install LangChain
pip install langchain langchain-openaiFirst LangChain program
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
# Initialize model (requires OpenAI API key)
llm = ChatOpenAI(model="gpt-3.5-turbo", api_key="YOUR_API_KEY")
# Send a message
response = llm.invoke([HumanMessage(content="Introduce yourself in one sentence")])
print(response.content)I am an AI assistant developed by OpenAI, designed to help users answer questions, complete tasks, and provide information.
Domestic model example
# Example with Zhipu AI
from langchain_community.chat_models import ChatZhipuAI
llm = ChatZhipuAI(model="glm-4", api_key="YOUR_ZHIPU_API_KEY")Core components
Prompt templates
from langchain_core.prompts import ChatPromptTemplate
template = """
You are a {role} expert. Please answer the following question in a {tone} tone:
{question}
"""
prompt = ChatPromptTemplate.from_template(template)
formatted = prompt.format(
role="Python",
tone="humorous",
question="What is a variable?"
)Chains
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
chain = prompt | llm | StrOutputParser()
result = chain.invoke({
"role": "history",
"tone": "vivid and fun",
"question": "Who was Qin Shi Huang?"
})
print(result)Retrieval‑augmented generation
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
loader = TextLoader("company_manual.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(docs, embeddings)
retriever = vectorstore.as_retriever()
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
chain = create_stuff_documents_chain(llm, retriever)Practical case: intelligent customer‑service bot
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
system_prompt = """
You are an intelligent customer‑service assistant for an e‑commerce company.
Please answer user questions in a friendly, professional manner.
If you don’t know the answer, be honest and suggest contacting human support.
"""
prompt = ChatPromptTemplate.from_messages([
("system", system_prompt),
("human", "{input}")
])
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
chain = prompt | llm | StrOutputParser()
while True:
user_input = input("👤 You: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("🤖 Bot: Thank you for contacting us, have a great shopping experience!")
break
response = chain.invoke({"input": user_input})
print(f"🤖 Bot: {response}")References
https://python.langchain.com.cn/
https://python.langchain.com/
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.
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.
